数组拼接从数组

时间:2017-02-03 15:51:17

标签: javascript arrays splice

var currentAge = 26;
var maxAge = 100;
var amountPerDay = 30.50;

var calculation = (((maxAge - currentAge) * 365) * amountPerDay);
console.log(calculation);
var stringCalc = calculation.toString().split('').splice(2, 0, "9");
console.log(stringCalc);

console.log(stringCalc)显示一个空数组。这与toString方法有关吗?

注意:我正在尝试添加字符串" 9"进入数组的中间,不从数组中删除任何内容。

3 个答案:

答案 0 :(得分:0)

bind()

var currentAge = 26; var maxAge = 100; var amountPerDay = 30.50; var calculation = (((maxAge - currentAge) * 365) * amountPerDay); console.log(calculation); var stringCalc = calculation.toString().split(''); console.log(stringCalc); stringCalc.splice(2, 0, "9"); console.log(stringCalc);返回取出的项目(在本例中为none),而不是返回拼接后的数组。

答案 1 :(得分:0)

splice不返回数组只是将其添加到现有数组中:

var currentAge = 26;
var maxAge = 100;
var amountPerDay = 30.50;

var calculation = (((maxAge - currentAge) * 365) * amountPerDay);
var numberArray = calculation.toString().split('')

numberArray.splice(2, 0, "9");
console.log(numberArray);

答案 2 :(得分:0)

您理解中缺少的链接是splice的返回值,它是已删除的项目。

var currentAge = 26;
var maxAge = 100;
var amountPerDay = 30.50;

var calculation = (((maxAge - currentAge) * 365) * amountPerDay);
console.log(calculation);
var stringCalc = calculation.toString().split('');
console.log(stringCalc);
// ["8", "2", "3", "8", "0", "5"]
console.log(stringCalc.splice(2, 0, "foo"));
// [] because no items were deleted, return value = array of deleted items
console.log(stringCalc)
// ["8", "2", "foo", 3", "8", "0", "5"]