Javascript 有条件的循环
Javascript for loop with condition
我正在阅读有关算法的可汗学院课程。我在 https://www.khanacademy.org/computing/computer-science/algorithms/insertion-sort/p/challenge-implement-insert .
After calling the insert function:
* value and the elements that were previously in array[0] to array[rightIndex], should be sorted in ascending order and stored in the elements from array[0] to array[rightIndex+1]. In order to do this, the insert function will need to make room for value by moving items that are greater than value to the right. It should start at rightIndex, and stop when it finds an item that is less than or equal to value, or when it reaches the beginning of the array. Once the function has made room for value, it can write value to the array.
我的尝试是:
var insert = function(array, rightIndex, value) {
var i = rightIndex;
for( array[i]> key ; 0; i-- ) {
array[i + 1] = array[i];
}
array[i]= value;
};
var array = [3, 5, 7, 11, 13, 2, 9, 6];
insert(array, 4, 2);
println("Array after inserting 2: " + array);
他们特别说他们想要 for 循环中的条件,但我不知道该怎么做。
var insert = function(array, rightIndex, value) {
// for( initial_value; condition; change the value for next iteration)
// && - returns true only when both are true.
for(var j = rightIndex; j >= 0 && array[j] > value; j--) {
array[j + 1] = array[j];
}
array[j + 1] = value;
};
我正在阅读有关算法的可汗学院课程。我在 https://www.khanacademy.org/computing/computer-science/algorithms/insertion-sort/p/challenge-implement-insert .
After calling the insert function: * value and the elements that were previously in array[0] to array[rightIndex], should be sorted in ascending order and stored in the elements from array[0] to array[rightIndex+1]. In order to do this, the insert function will need to make room for value by moving items that are greater than value to the right. It should start at rightIndex, and stop when it finds an item that is less than or equal to value, or when it reaches the beginning of the array. Once the function has made room for value, it can write value to the array.
我的尝试是:
var insert = function(array, rightIndex, value) {
var i = rightIndex;
for( array[i]> key ; 0; i-- ) {
array[i + 1] = array[i];
}
array[i]= value;
};
var array = [3, 5, 7, 11, 13, 2, 9, 6];
insert(array, 4, 2);
println("Array after inserting 2: " + array);
他们特别说他们想要 for 循环中的条件,但我不知道该怎么做。
var insert = function(array, rightIndex, value) {
// for( initial_value; condition; change the value for next iteration)
// && - returns true only when both are true.
for(var j = rightIndex; j >= 0 && array[j] > value; j--) {
array[j + 1] = array[j];
}
array[j + 1] = value;
};