JavaScript cross-browser: Is it safe to treat a string as array?

£可爱£侵袭症+ 提交于 2019-12-10 02:48:07

问题


Is this code safe in all major browsers?

var string = '123'
alert(string[1] == '2') // should alert true

回答1:


No, it's not safe. Internet Explorer 7 doesn't support accessing strings by index.

You have to use the charAt method to be compatibale with IE7:

var string = '123';
alert(string.charAt(1) == '2');



回答2:


Everything in JavaScript is an object; arrays, functions, strings, everything. The piece of code you put up is perfectly valid, although a little confusing - there are much better ways of doing that

var str = '123';
str[1] === '2'; // true, as you've just discovered (if you're not in IE7)
// Better ways:
str.indexOf('2'); // 1
str.charAt(1); // '2'
str.substr(1, 1); // '2'
str.split(''); // ['1', '2', '3']

The better ways make sure anyone else reading your code (either someone else or yourself in 6 months time) don't thing that str is an array. It makes your code a lot easier to read and maintain




回答3:


I tested in IE7, IE8, Safari, Chrome, and FF. All worked just fine!

EDIT just for kicks it works in Konqueror also! Js Fiddle example




回答4:


I don't really see why you can't do that...though alternatively, you can use .substring()




回答5:


It will work. It might be a problem if you decide to use browser specific functions (I.E xmlhttp=new ActiveXObject("Microsoft.XMLHTTP"); only works in internet explorer)



来源:https://stackoverflow.com/questions/5599881/javascript-cross-browser-is-it-safe-to-treat-a-string-as-array

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!