Javascript创建具有固定值但与另一个数组的列量匹配的数组(Javascript create array with fixed value but matching column amount from another array)
我有一个动态构建的数组,所以它可以改变。
它基本上是这样的:
["t1", "something", "bird", "dog", "cow", "fish"]我需要做的是计算它们中有多少个并创建另一个具有相同数量的列的数组,但所有数组的值都为1。
例如,如果数组是:
["bird", "dog", "cow", "fish"]然后它创建一个数组:
[1, 1, 1, 1]如果数组是:
["bird", "fish"]然后它创建一个数组:
[1, 1]我怎样才能做到这一点?
I have an array which is built from data dynamically, so it can change.
It's basically this:
["t1", "something", "bird", "dog", "cow", "fish"]What I need to do is to count how many of them there are and create another array with the same amount of columns but all with the value of 1.
For example, if the array is:
["bird", "dog", "cow", "fish"]then it creates an array of:
[1, 1, 1, 1]If the array is:
["bird", "fish"]then it creates an array of:
[1, 1]How can I do this?
最满意答案
只需创建一个等长的新数组并使用fill函数。
var myArray = ["dog","cat","monkey"]; var secondArray = new Array(myArray.length).fill(1);Just create a new array of equal length and use the fill function.
var myArray = ["dog","cat","monkey"]; var secondArray = new Array(myArray.length).fill(1);更多推荐
发布评论