簡體   English   中英

Javascript:如何編輯從7,8,9,10到07,08,09,10的數組元素?

[英]Javascript: how to Edit array elements from 7,8,9,10 to 07,08,09,10?

我有一個數字數組,例如[7,8,9,10]。 我需要將每個數組元素都設置為一位,以使其變為07、08、09等。

有任何想法嗎?

您應該嘗試這樣的事情:

 var data = [7, 8, 9, 10]; data = data.map(function(x) { return (x<10 && x>0) ? "0" + x : x; }); console.log(data); 

最簡單最基本的方法:

 var index; var a = [7, 8, 9,10]; for (index = 0; index < a.length; ++index) { if(a[index]>0 && a[index]<10) alert((0).toString()+a[index].toString()); else alert(a[index]) } 

var numbers = [7,8,9,10];
function pad(n) {
return (n < 10) ? ("0" + n) : n;
}

for (i = 0; i < numbers.length; i++) {
    if(numbers[i] < 10){
     var n = numbers[i];
     pad(n);
    }
}

尚未對此進行測試,但是要遍歷數字數組並在數字小於10的情況下添加零,然后由您決定如何處理,更新數組值或將其推入新值。

您需要在數組的每個元素上使用零填充。 只需參考此答案https://stackoverflow.com/a/1267338/1486897並使用Array.map的給定函數Array.map 產生的代碼將類似於:

// Here you should put the zeroFill function implementation

var data = [7, 8, 9, 10];

data = data.map(function(number) {
  return zeroFill(number, 2);
});

console.log(data);

為了提供更通用的解決方案,下面的函數采用一個可選的第二個參數,使您可以指定數組中每個字符串應保持的時間。 如果未提供,則使用最長項目的長度,並用前導零填充其他項目以匹配該長度。 在計算字符串長度時,它也忽略負數中的減號,並允許您根據需要操縱負數(只需在函數中編輯最后一個條件)-我已經將負數包裝在括號中。

 var arr=[7,8,9,10]; pad(arr); console.log(arr);//["07","08","09","10"] arr=[7,8,-9,10] pad(arr,3); console.log(arr);//["007","008","(009)","010"] function pad(array){ var len,neg,x=1, max=arguments[1]||(function(){ array.forEach(function(item){ if((len=Math.abs(item).toString().length)>x) x=len; }); return x; })(); array.forEach(function(item,index){ neg=item<0; len=(item=Math.abs(item).toString()).length; for(;len<max;len++) item="0"+item; if(neg) item="("+item+")"; array[index]=item; }); }; 

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM