我有一个数组和一个变量,该变量将显示整数值,基于该值,我需要向该数组中添加空白元素。例如,值为4时,我应该得到结果['','', ”,”,“ chart1”,“ chart2”,“ chartr3”]。这是下面的代码,例如,我在这里进行了硬编码
<p>How to add blank element to an array based on value in javascript</p>
var count = 4;
var array = ['chart1','chart2','chartr3'];
console.log(array);
var finalarray[] ;
console.log(finalarray);//['','','','','chart1','chart2','chartr3'];
答案 0 :(得分:0)
尝试循环吗?
var count = 4;
var array = ["chart1", "chart2", "chart3"];
var finalArray = array;
for (var i = 0; i < count; i++) {
finalArray.unshift("");
}
console.log(finalArray);
注意: unshift()方法在Internet Explorer 8及更早版本中无法正常工作:将插入值,但返回值将是不确定的。 / p>
如果您希望在单击按钮时此数组增加,可以尝试如下操作:
var array = ["after", "after2", "after3"];
// This will set the span 'originalArray' to display 'array'
document.getElementById("originalArray").innerHTML = array;
// prependValueToArray:
// - This function will add a value e.g: "" to your specified array 'x' ammount of times.
function prependValueToArray(array, ammount, value) {
var resultArray = array;
for (var i = 0; i < ammount; i++) {
resultArray.unshift(value);
}
// This will change the value inside the 'resultArray' span to the new array
document.getElementById("resultArray").innerHTML = resultArray;
}
<p>
<strong>
Original:
</strong>
<br/>
[
<span id="originalArray"></span>
]
</p>
<button onclick="prependValueToArray(array, 1, 'before');">Click me!</button>
<p>
<strong>
Result:
</strong>
<br/>
[
<span id="resultArray"></span>
]
</p>
答案 1 :(得分:0)
您可以尝试使用unshift
var array = ['chart1','chart2','chartr3'];
var count = 4;
for (var i = 1; i++; i <= count) {
array.unshift(' ');
}
编辑。要在每次点击(jquery)中触发它
var start_array = ['chart1','chart2','chartr3'];
$('.element-clicked').on('click', function(e) {
start_array.unshift(' ');
});
答案 2 :(得分:0)
如果要使用功能。和var finalarray [];是错误的。
var array = ["chart1","chart2","chartr3"];
var count = 4;
function myFunction() {
var finalarray=[] ;
for(var i=0;i< 4;i++){
finalarray.push("") ;
}
finalarray.push("chart1") ;
finalarray.push("chart2") ;
finalarray.push("chartr3") ;
console.log(finalarray);
}
<button onclick="myFunction()">Click me</button>
答案 3 :(得分:-1)
var count = 4; finalarray [i] =''; }
for(var i = 0; i