拆分变量并推入数组

时间:2017-04-12 07:14:44

标签: javascript jquery arrays

我有一个包含几个逗号分隔值的变量。我想将它们分开并将它们按整数推入数组中,但我无法弄明白。

我以下......

globArr = [];
arr = "1,4,3,2,4,2,4";

var answ = arr.split(',');
globArr.push(parseInt(answ));

console.log(globArr);

https://jsfiddle.net/d7hke7gq/

有谁能告诉我哪里出错了?

2 个答案:

答案 0 :(得分:0)

您需要遍历answers数组以推送每个值:



let globArr = [];
let arr = "1,2,3,4,5,6,7,8,9,10";
let answ = arr.split(',');
answ.forEach(function(obj){
      globArr.push(parseInt(obj,10));
});
console.log(globArr);




答案 1 :(得分:0)

你走了:

Updated fiddle

globArr = [];
arr = "1,4,3,2,4,2,4";

var answ = arr.split(',');
$.each(answ, function(){
globArr.push(parseInt(this));
});


console.log(globArr);