JavaScript 访问字符串字符作为数组
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/4051385/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
JavaScript access string chars as array
提问by Francisc
Is it ok to do this:
这样做可以吗:
var myString="Hello!";
alert(myString[0]); // shows "H" in an alert window
Or should it be done with either charAt(0) or substr(0,1)? By "is it ok" I mean will it work on most browsers, is there a best practice recommandation that says otherwise etc.
还是应该用 charAt(0) 或 substr(0,1) 来完成?“可以吗”我的意思是它可以在大多数浏览器上工作,是否有最佳实践建议,否则等等。
Thank you.
谢谢你。
采纳答案by Saul
Using charAt
is probably the best idea since it conveys the intent of your code most accurately. Calling substr
for a single character is definitely an overkill.
使用charAt
可能是最好的主意,因为它最准确地传达了代码的意图。调用substr
单个字符绝对是一种矫枉过正。
alert(myString.charAt(0));
回答by Tim Down
Accessing characters as numeric properties of a string is non-standard prior to ECMAScript 5 and doesn't work in all browsers(for example, it doesn't work in IE 6 or 7). You should use myString.charAt(0)
instead when your code has to work in non-ECMAScript 5 environments. Alternatively, if you're going to be accessing a lot of characters in the string then you can turn a string into an array of characters using its split()
method:
在 ECMAScript 5 之前,将字符作为字符串的数字属性访问是非标准的,并且不适用于所有浏览器(例如,它不适用于 IE 6 或 7)。myString.charAt(0)
当您的代码必须在非 ECMAScript 5 环境中工作时,您应该使用它。或者,如果您要访问字符串中的大量字符,则可以使用其split()
方法将字符串转换为字符数组:
var myString = "Hello!";
var strChars = myString.split("");
alert(strChars[0]);
回答by James
2018 answer: Yes it is OKto access strings like arrays.
2018 年回答:是的,可以访问数组之类的字符串。
The syntax is clear and concise. IE6 and IE7 are long gone. I see no reason not to use it.
语法清晰简洁。IE6 和 IE7 早已不复存在。我认为没有理由不使用它。
回答by Eric Bishard
In ES6 we can use destructuring since a string can be treated as an array:
在 ES6 中,我们可以使用解构,因为字符串可以被视为数组:
const [...rest] = 'Hello!';
console.log(rest)
> Array ["H", "e", "l", "l", "o", "!"]
console.log(rest[0])
> "H"