[英]Print the number of values as take from the Index value from array
最近參加了采訪,有人問如下問題:
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);
}
});
提前致謝!
您可以迭代數組並迭代計數。 然后顯示新字符串。
var array = [0, 1, 2, 3, 4, 5]; array.forEach(function (a, i) { var s = ''; while (i--) { s += a; } console.log ('temp' + s + ':' + s); });
使用ES6 模板字符串和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); })
由於ES5中不存在String.prototype.repeat
,因此有一些技巧可以生成具有重復字符的特定長度的字符串: Array(initialCapacity)
將創建一個新數組,其空插槽等於您傳入的數字,然后可以使用Array.prototype.join
將數組的所有成員連接成一個字符串。 參數.join
是您想要的分隔符,因此,例如,您可以執行以下操作
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,因為加入時少了一個字符。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.