Javascript 如何在数组中存储数据,但包含上一个值?
我有一个名为targetPercentage的数组Javascript 如何在数组中存储数据,但包含上一个值?,javascript,arrays,Javascript,Arrays,我有一个名为targetPercentage的数组 targetPercentage = [0,33,77,132] 如何将其分为长度为2但包含上一个值的块? 如果可能的话,还可以将其转换为一个Javascript对象数组,其中包含其各自的属性 示例输出: [0,33] [33,77] [77,132] 将其设置为对象数组的输出示例: thresholds : [ {from:0,to:33},{from:33,to:77},{from:77,to:132} ] 类似于此,但包含上一个值
targetPercentage = [0,33,77,132]
如何将其分为长度为2但包含上一个值的块?
如果可能的话,还可以将其转换为一个Javascript对象数组,其中包含其各自的属性
示例输出:
[0,33]
[33,77]
[77,132]
将其设置为对象数组的输出示例:
thresholds : [ {from:0,to:33},{from:33,to:77},{from:77,to:132} ]
类似于此,但包含上一个值。您可以使用
array从头开始创建数组。从访问i
th元素以及每次迭代中的i+1
th元素以创建对象:
const targetPercentage=[0,33,77132];
const result=Array.from(
{length:targetPercentage.length-1},
({from:targetPercentage[i],to:targetPercentage[i+1]})
);
控制台日志(结果)代码>const targetPercentage=[0,33,77,132]
常数阈值=[]
for(设i=0;i
数组函数片(初始值,计数)-将给定数组分为3个块,每个块包含2个元素
临时数组将具有[0,33]、[33,77]、[77132]
var i,j,temparray,chunk = 2;
result=[];for (i=0,j=targetPercentage.length; i<j-1; i++) {
temparray = targetPercentage.slice(i,i+chunk);
result.push({from:temparray[0],to:temparray[1]});
}
console.log(result);
vari,j,temparray,chunk=2;
结果=[];对于(i=0,j=targetPercentage.length;i您可以尝试以下方法:
function binData(array) {
let result = []
for (let i=0; i<array.length-1; i++) {
result.push({
from: array[i],
to: array[i+1]
})
}
return result
}
函数binData(数组){
让结果=[]
因为(让i=0;i[from:0,to:33]
是无效的语法,我猜你的意思是作为一个对象,而不是数组?他只是把它称为一个例子。@CertainPerformance修复了它。对此表示歉意。呃,它仍然无效-对象需要同时具有键和值。我猜你在寻找[{from:0,to:33},{from:33,to:77},{from:77,to:132}]
或[[0,33],[33,77],[77132]
虽然这段代码可能(或可能不会)解决问题,但一个好的答案应该解释代码做什么以及它如何解决问题。虽然这段代码可能(或可能不会)解决问题,但一个好的答案应该解释代码做什么以及它如何解决问题。
function binData(array) {
let result = []
for (let i=0; i<array.length-1; i++) {
result.push({
from: array[i],
to: array[i+1]
})
}
return result
}