我想将前一个数字添加到javascript数组中的当前数字中吗?

时间:2019-03-04 21:26:00

标签: javascript

var结果应为[4,8,15,21,11]。 但是我得到了[4,4,4,4,4]。 我只是想不通

extension String {

    /// Generates a `UIImage` instance from this string using a specified
    /// attributes and size.
    ///
    /// - Parameters:
    ///     - attributes: to draw this string with. Default is `nil`.
    ///     - size: of the image to return.
    /// - Returns: a `UIImage` instance from this string using a specified
    /// attributes and size, or `nil` if the operation fails.
    func image(withAttributes attributes: [NSAttributedString.Key: Any]? = nil, size: CGSize? = nil) -> UIImage? {
        let size = size ?? (self as NSString).size(withAttributes: attributes)
        return UIGraphicsImageRenderer(size: size).image { _ in
            (self as NSString).draw(in: CGRect(origin: .zero, size: size),
                                    withAttributes: attributes)
        }
    }

}

3 个答案:

答案 0 :(得分:1)

地图功能给您带来价值,而我。您使用它有点错误,并且您也不需要for循环。同样在forloop中,您覆盖了map函数中的i变量。

var numbers = [1,3,5,10,11];
var result = numbers.map(function(num, i, arr){
  if (arr[i + 1]) {
    return num + arr[i + 1];
  }
  return num;
});
console.log('result', result);
console.log('expected',  [4, 8, 15, 21, 11]);

答案 1 :(得分:1)

您无需在map方法内使用另一个循环。此外,您将覆盖i定义为map当前值的值。

document.body.innerText = [1, 3, 5, 10, 11].map((x, i, arr) => x + (arr[i + 1] || 0))
// --> For each iteration, returns its value + (next iteration's value, or 0 if it's the last one).

答案 2 :(得分:0)

一种简化的实现方式是下一个:

var numbers = [1,3,5,10,11];

var result = numbers.map(
    (x, idx, arr) => idx < arr.length - 1 ? x + arr[idx + 1] : x
);

console.log(result);
.as-console {background-color:black !important; color:lime;}
.as-console-wrapper {max-height:100% !important; top:0;}

请注意,与Array.map()关联的回调采用以下参数:

var new_array = arr.map(function callback(currentValue[, index[, array]])
{
    // Return element for new_array
}[, thisArg])

位置:

  • currentValue::数组中正在处理的当前元素。
  • indexOptional 数组中正在处理的当前元素的索引。
  • arrayOptional 。调用了数组映射。

如果您不熟悉map(),甚至可以使用传统的for循环:

var numbers = [1,3,5,10,11];
var result = [];

for (let i = 0; i < numbers.length; i++)
{
    if (numbers[i + 1])
        result.push(numbers[i] + numbers[i + 1]);
    else
        result.push(numbers[i]);
}

console.log(result);
.as-console {background-color:black !important; color:lime;}
.as-console-wrapper {max-height:100% !important; top:0;}