如何将字符串拆分为字符数组? [英] How do I split a string into an array of characters?

查看:146
本文介绍了如何将字符串拆分为字符数组?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

var s = "overpopulation";
var ar = [];
ar = s.split();
alert(ar);

我想将string.split一个单词转换成字符数组。

I want to string.split a word into array of characters.

上面的代码似乎不起作用 - 它将overpopulation作为Object返回..

The above code doesn't seem to work - it returns "overpopulation" as Object..

如何将其拆分为字符数组,如果原始字符串不包含逗号和空格?

How do i split it into array of characters, if original string doesn't contain commas and whitespace?

推荐答案

您可以拆分空字符串:

var chars = "overpopulation".split('');






如果你只想访问一个字符串类似于数组的方式,你可以不用拆分

var s = "overpopulation";
for (var i = 0; i < s.length; i++) {
    console.log(s.charAt(i));
}






您还可以访问每个使用普通数组语法的索引字符。但请注意,字符串是不可变的,这意味着您不能使用此方法设置字符的值,并且IE7不支持它(如果这仍然对您很重要)。


You can also access each character with its index using normal array syntax. Note, however, that strings are immutable, which means you can't set the value of a character using this method, and that it isn't supported by IE7 (if that still matters to you).

var s = "overpopulation";

console.log(s[3]); // logs 'r'

这篇关于如何将字符串拆分为字符数组?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆