我的数组是:
var array = ["author", "1", "2", "3", "5", "6"]
单击按钮,我试图将作者移到数组的第一个位置,而不是第二个位置和结尾。
答案 0 :(得分:1)
您可以对索引进行闭包以与下一个交换,并检查是否可以交换。如果不返回数组,则交换元素。
ALTER FUNCTION [dbo].[fnc_2019_test]
(@m_id INT, @fra DATE, @til DATE)
RETURNS INT
AS
BEGIN
RETURN
(SELECT
SUM(ISNULL(e.FORBRUK, 0) * DATEDIFF(D, e.FRADATO, @til))
FROM
dbo.mlr_eos_avl e
WHERE
e.MÅLER_ID = @m_id
AND @fra < e.DATO
AND DATEADD(D, -1, @til) >= e.FRADATO)
END
const
swap = (a, i = 0) => () => {
if (i + 1 >= a.length) return a;
[a[i + 1], a[i]] = [a[i], a[i + 1]];
i++;
return a;
};
var array = ["author", "1", "2", "3", "5", "6"],
s = swap(array);
console.log(...array);
console.log(...s());
console.log(...s());
console.log(...s());
console.log(...s());
console.log(...s());
console.log(...s());
,它从以下索引中展开一个长度为一项的拼接数组。
splice
答案 1 :(得分:0)
单击按钮,将获得indexOf
作者,在另一个变量中,将元素添加到下一个索引。如果数组中的下一个位置不是undefined
,则将author
的位置与紧接的下一个元素交换
var array = ["author", "1", "2", "3", "5", "6"]
function shiftAuthor() {
// get index of author in the array
let currPosition = array.indexOf('author');
// if the index of author +1 is not undefined
if (array[currPosition + 1] !== undefined) {
// get the element at the next index of author
let elemAtNextPos = array[currPosition + 1];
// interchange their position
array[currPosition + 1] = 'author'
array[currPosition] = elemAtNextPos;
}
console.log(array)
}
<button type='button' onclick='shiftAuthor()'> Shift Author </button>