Javascript-帮助将ES6(箭头函数)转换为非ES6代码



我有这两个带有jQuery验证插件的验证例程。它们工作得很好,但我们的JS压缩器不喜欢ES6功能。我是ES6的新手。我可以处理简单的转换,但我无法处理这些行:

let total = v.reduce((acc, n) => {
return acc + n;
}, 0);

下面是两个完整的功能,我知道我可以替换";设";利用var";,但是当运算符的左侧是另一个函数时,我该如何重写箭头语句。那就是我迷失的地方。有人知道吗?

// ABN
$.validator.addMethod('ABN', function(v, element, p) {
if (this.optional(element)){return true};

const weights = new Array(10, 1, 3, 5, 7, 9, 11, 13, 15, 17, 19);
// Convert to string and remove all white space
v = v.toString().replace(/s/g, "");
// Split it to number array
v = v.split('').map(n => parseInt(n));
// Subtract 1 from the first (left-most) digit of the ABN to give a new 11 digit number
v[0] = v[0] - 1;
// Multiply each of the digits in this new number by a "weighting factor" based on its position as shown in the table below
v = v.map((n, i) => n * weights[i]);
// Sum the resulting 11 products
let total = v.reduce((acc, n) => {
return acc + n;
}, 0);
// Divide the sum total by 89, noting the remainder
if(total % 89 === 0) {
return true;
} else {
return false;
}

});
// ACN
$.validator.addMethod('ACN', function(v, element, p) {
if (this.optional(element)){return true};
const weights = new Array(8, 7, 6, 5, 4, 3, 2, 1);
// Convert to string and remove all white space
v = v.toString().replace(/s/g, "");
// Split it to number array
v = v.split('').map(n => parseInt(n));
// Set the check digit and remove it 
let checkDigit = v.pop();
// Apply weighting to digits 1 to 8.
v = v.map((n, i) => n * weights[i]);
// Sum the products
let total = v.reduce((acc, n) => {
return acc + n;
}, 0);
// Divide by 10 to obtain remainder
let calculatedCheckDigit = (10 - (total % 10)) % 10;
// calculatedCheckDigit should match check digit
if(calculatedCheckDigit === checkDigit) {
return true;
} else {
return false;
}

});

我认为您的代码中已经有了一个很好的例子,您可以在另一个函数中传递一个函数,这里是:

// ABN
$.validator.addMethod('ABN', function(v, element, p) {

基本上,您需要做的是用function ():替换() =>

let total = v.reduce(function(acc, n) {
return acc + n;
}, 0);

var total = v.reduce(function(acc, n) {
return acc + n;
}, 0);

相关内容

  • 没有找到相关文章

最新更新