我的代码
const upperCase = 'QWERTYUIOPASDFGHJKLZXCVBNM'.split('');
const lowerCase = 'qwertyuiopasdfghjklzxcvbnm'.split('');
const numbers = '1234567890'.split('');
const symbols = '@#£&*()'"%-+=/;:,.€$¥_^[]{}§|~…\<>!?'.split('');
var exclude = [];
var fullList = [];
var allowUpperCase = true;
var allowLowerCase = true;
var allowSymbols = true;
var allowNumbers = true;
function genList() {
if (allowUpperCase) {
fullList.concat(upperCase);
}
if (allowLowerCase) {
fullList.concat(lowerCase);
}
if (allowSymbols) {
fullList.concat(symbols);
}
if (allowNumbers){
fullList.concat(numbers)
}
}
genList();
console.log(fullList);
它应该做什么:检查用户是否需要这些字符然后将它们添加到" fullList "数组
但是当我做genList
和console.log(fullList)
时,它似乎是空的[]
为什么?
由于您希望改变fullList
数组,您可以使用Array#push()
并传播传递的数组,而不是使用Array#concat()
。
这避免了在每个条件匹配上创建一个新的数组,而只是简单地扩展了现有的数组。
const upperCase = 'QWERTYUIOPASDFGHJKLZXCVBNM'.split('');
const lowerCase = 'qwertyuiopasdfghjklzxcvbnm'.split('');
const numbers = '1234567890'.split('');
const symbols = '@#£&*()'"%-+=/;:,.€$¥_^[]{}§|~…\<>!?'.split('');
var exclude = [];
var fullList = [];
var allowUpperCase = true;
var allowLowerCase = true;
var allowSymbols = true;
var allowNumbers = true;
function genList() {
if (allowUpperCase) {
fullList.push(...upperCase);
}
if (allowLowerCase) {
fullList.push(...lowerCase);
}
if (allowSymbols) {
fullList.push(...symbols);
}
if (allowNumbers) {
fullList.push(...numbers)
}
}
genList();
console.log(fullList.join(', '));
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/concat
Array concat方法不修改当前数组,而是返回一个新数组。像这样修改方法&会成功的。
function genList() {
if (allowUpperCase) {
fullList = fullList.concat(upperCase);
}
if (allowLowerCase) {
fullList = fullList.concat(lowerCase);
}
if (allowSymbols) {
fullList = fullList.concat(symbols);
}
if (allowNumbers){
fullList = fullList.concat(numbers)
}
}
数组方法concat
(参见MDN Web Docs)不会改变原来的数组,它返回一个新的数组。
const upperCase = 'QWERTYUIOPASDFGHJKLZXCVBNM'.split('');
const lowerCase = 'qwertyuiopasdfghjklzxcvbnm'.split('');
const numbers = '1234567890'.split('');
const symbols = '@#£&*()'"%-+=/;:,.€$¥_^[]{}§|~…\<>!?'.split('');
var exclude = [];
var fullList = [];
var allowUpperCase = true;
var allowLowerCase = true;
var allowSymbols = true;
var allowNumbers = true;
function genList() {
if (allowUpperCase) {
fullList = fullList.concat(upperCase);
}
if (allowLowerCase) {
fullList = fullList.concat(lowerCase);
}
if (allowSymbols) {
fullList = fullList.concat(symbols);
}
if (allowNumbers){
fullList = fullList.concat(numbers);
}
console.log(fullList);
}
genList();