简体   繁体   English

数组拼接从数组中删除所有元素

[英]Array splice removes all elements from array

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) shows an empty array. console.log(stringCalc) 显示一个空数组。 Does this have something to do with the toString method?这与 toString 方法有关吗?

Note: I am trying to add the string "9" into the middle of the array, not remove anything from the array.注意:我试图将字符串“9”添加到数组的中间,而不是从数组中删除任何内容。

The missing link in your understanding is the return value of splice, which are the deleted items.你理解中缺失的环节是 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"]

 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);

splice() returns the items taken out (in this case none), not the array after the splice takes place. splice()返回取出的项目(在这种情况下没有),而不是拼接发生后的数组。

splice does not return an array just adds it into the existing array: 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);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM