最近参加面试,有人问了这样的问题:
var array = [0,1,2,3,4,5];
输出:
temp:
temp1:1
temp22:22
temp333:333
temp4444:4444
temp55555:55555
我尝试了下面的代码,它工作正常,但是这个例子有没有最好的解决方案:
array.forEach(function(item,index){
var text ="";
if(index >= 2){
for(var j =1; j <= index; j++){
text += index;
}
console.log("temp"+text + ":" + text);
}else{
console.log("temp"+index + ":" + index);
}
});
提前致谢!
最佳答案
使用 ES6 template strings和 String.prototype.repeat
var array = [0,1,2,3,4,5];
array.forEach(item => {
const text = String(item).repeat(item);
console.log(`temp${text}: ${text}`);
})
同样的代码被翻译成 ES5 - 这将适用于从 IE9 及以上版本开始的所有浏览器。
var array = [0,1,2,3,4,5];
array.forEach(function(item) {
var text = Array(item+1).join(item);
console.log("temp" + text + ": " + text);
})
自 String.prototype.repeat
ES5 中不存在,有一些 hack 可以生成具有重复字符的特定长度的字符串:
Array(initialCapacity)
将创建一个新数组,其空槽等于您传入的数字 Array.prototype.join
然后可用于将数组的所有成员连接成一个字符串。参数.join
take 是您想要的分隔符,因此,例如您可以执行类似的操作
var joinedArray = ["a","b","c"].join(" | ");
console.log(joinedArray);
但是,在这种情况下,数组的每个成员都是空白的,因为数组只有空白槽。因此,加入后,除非您指定分隔符,否则您将得到一个空白字符串。您可以利用它来获得重复功能,因为您本质上是在做这样的事情
//these produce the same result
var repeatedA = ["","",""].join("a");
var repeatedB = Array(3).join("b");
console.log("'a' repeated:", repeatedA);
console.log("'b' repeated:", repeatedB);
使用Array
函数,您可以将其缩放到您想要的任意重复次数。唯一的技巧是创建数组时需要加 1,因为加入时会少一个字符。
关于javascript - 打印从数组的索引值中获取的值的数量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40894705/