如何在JS中将循环数组的元素赋值给另一个?

时间:2016-12-14 05:45:20

标签: javascript arrays loops

...

function ar(farray) {
    var array = farray.slice(0, 2);
    for (i = 2; i <= farray.length; i++) {
        if (array[0] < farray[i]) {
            //Here is the problem.Why i can 't just (re)assign value, referencing to another array? 
            //need to be assigned-copied-rewrited!!
            array[0] = farray[i];
        }
    }
    return array[0] + array[1];
}

创建一个函数,该函数返回给定最小4个整数数组的两个最低正数之和。不会传递浮点数或空数组。

function sumTwoSmallestNumbers(numbers) {  
var array=numbers.slice(0,2);
array.sort(function(a,b){return b-a});
array[0]=numbers[0];
array[1]=numbers[1];
for (i=2;i<=numbers.length; i++){
if  (numbers[i]<array[0] || numbers[i]<array[1]) {
 if (numbers[i]<array[0]) {
 array[0]=numbers[i];
} else {
array[1]=numbers[i];
     }           
  }

解决了!

//My sorting relies on positions of value in 'array', therefore for every 'for' loop I need prepared positions
 array.sort(function(a,b){return b-a});
}
return array[0]+array[1];
};

1 个答案:

答案 0 :(得分:0)

为什么你需要另一个阵列?

&#13;
&#13;
function ar(farray) {
    var a = farray[0];
    for (i = 2; i <= farray.length; i++) {
        if (a < farray[i]) 
            a = farray[i];
    }
    return a + farray[1];
}
&#13;
&#13;
&#13;