将字符串转换为数组

turning a string into an array

本文关键字:数组 转换 字符串      更新时间:2023-09-26
var objectHTMLCollection = document.getElementsByTagName("select"),
string = [].map.call( objectHTMLCollection, function(node){
    return node.id || "";
}).join(" ");

我有这段代码,可以将[object HTMLCollection]转换为字符串,我想将其转换为数组。所以说他们的输出是hello world I am here会变得[hello,world,I,am,here]

您可以使用split(" ")

var stringArray = string.split(" "); 

或者你可以在准备字符串的同时准备数组,见下面的代码

var stringArray = new Array();
var objectHTMLCollection = document.getElementsByTagName("select"),
string = [].map.call( objectHTMLCollection, function(node){
    stringArray.push(node.id);
    return node.id || "";
}).join(" ");

Map 已经返回了一个数组。无需将其转换为字符串然后又变回数组。

var objectHTMLCollection = document.getElementsByTagName("select"),
idarray = [].map.call( objectHTMLCollection, function(node){
    return node.id || "";
}), string = idarray.join(' ');
document.write('<div>String: ' + string + '<div>');
document.write('Array: ' + JSON.stringify(idarray) + '<div>');
<select id='dsada1'></select>
<select id='dsada2'></select>
<select></select>
<select id='dsada4'></select>
<select id='dsada5'></select>
<select id='dsada6'></select>
<br/><br/>