我正在學習 Javascript,我想知道將這個:[1,8] 轉換成這個:[1,2,3,4,5,6,7,8] 的最優雅的方法是什么?
非常感謝!
uj5u.com熱心網友回復:
const argarray = [1, 8]
const countToN = (array) => {
// init results array
let res = []
// start at the first value array[0] go *up to* the second array[1]
for (let i = array[0]; i <= array[1]; i ) {
res.push(i)
}
// return the result
return res
}
console.log(countToN([1, 10]))
這將適應你想要做的事情,但它相當脆弱。您必須檢查它是否是一個陣列并且它只有 2 個值。如果您有其他要求,我可以對此進行修改以解決問題。
uj5u.com熱心網友回復:
這是一個沒有回圈的解決方案。請注意,這只適用于正數。它支持任何長度的陣列,但始終將結果基于第一個和最后一個值。
const case1 = [1, 8];
const case2 = [5, 20];
const startToEnd = (array) => {
const last = array[array.length - 1];
const newArray = [...Array(last 1).keys()];
return newArray.slice(array[0], last 1);
};
console.log(startToEnd(case1));
console.log(startToEnd(case2));
這是一個也適用于負值的解決方案:
const case1 = [-5, 30];
const case2 = [-20, -10];
const case3 = [9, 14];
const startToEndSolid = (array) => {
const length = array[array.length - 1] - array[0] 1;
if (length < 0) throw new Error('Last value must be greater than the first value.');
return Array.from(Array(length)).map((_, i) => array[0] i);
};
console.log(startToEndSolid(case1));
console.log(startToEndSolid(case2));
console.log(startToEndSolid(case3));
uj5u.com熱心網友回復:
一個簡單的for回圈就可以了。這是一個具有錯誤檢查的示例,并允許您向后和向前(即[1, 8]和[1, -8])進行范圍。
function range(arr) {
// Check if the argument (if there is one) is
// an array, and if it's an array it has a length of
// of two. If not return an error message.
if (!Array.isArray(arr) || arr.length !== 2) {
return 'Not possible';
}
// Deconstruct the first and last elements
// from the array
const [ first, last ] = arr;
// Create a new array to capture the range
const out = [];
// If the last integer is greater than the first
// integer walk the loop forwards
if (last > first) {
for (let i = first; i <= last; i ) {
out.push(i);
}
// Otherwise walk the loop backwards
} else {
for (let i = first; i >= last; i--) {
out.push(i);
}
}
// Finally return the array
return out;
}
console.log(range([1, 8]));
console.log(range('18'));
console.log(range());
console.log(range([1]));
console.log(range([-3, 6]));
console.log(range([9, 16, 23]));
console.log(range([4, -4]));
console.log(range([1, -8, 12]));
console.log(range(null));
console.log(range(undefined));
console.log(range([4, 4]));
附加檔案
- 解構賦值
轉載請註明出處,本文鏈接:https://www.uj5u.com/shujuku/490957.html
標籤:javascript 数组
上一篇:d3根據高度改變條形圖顏色
