Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

创建包含10个1的数组 多种方法 #105

Open
Sunny-117 opened this issue Nov 3, 2022 · 5 comments
Open

创建包含10个1的数组 多种方法 #105

Sunny-117 opened this issue Nov 3, 2022 · 5 comments

Comments

@Sunny-117
Copy link
Owner

No description provided.

@vuemenow
Copy link

vuemenow commented Feb 8, 2023

菜鸟一枚,只能想出一些脱裤子放屁的方法,哈哈,各位大佬轻点喷

// 字面量构造
let nums = [1, 1, 1, 1, 1, 1, 1, 1, 1, 1]
// 构造函数+填充数组
let nums = new Array(10);
nums.fill(1, 0, num.length); 
// ES6: Array.of(),将参数依次转化为数组项
let nums = Array.of(1, 1, 1, 1, 1, 1, 1, 1, 1, 1) 
// ES6: Array.from(),基于其他对象创建新数组
let str = '1111111111'
let nums = Array.from(str, (val) => parseInt(val))

@bearki99
Copy link

const arr = new Array(10).fill(1);
const arr2 = [];
for(let i = 0; i < 10; i++) arr2[i] = 1;
const arr3 = [1, 1, 1, 1, 1, 1, 1, 1, 1, 1];
const arr4 = [];
let num = 10;
while(num--) arr4.splice(0, 0, 1);

@Tylermeek
Copy link

// 创建包含10个1的数组 多种方法
let arr1 = [1, 1, 1, 1, 1, 1, 1, 1, 1, 1];
let arr2 = new Array(10).fill(1);
let arr3 = [];
let arr4 = [];
let arr5 = [];
let num = 0;
while (num < 10) {
  arr3.push(1);
  arr4.splice(0, 0, 1);
  arr5 = arr5.concat([1]);
  num++;
}
// ES6: Array.of(),将参数依次转化为数组项,这里演示所以直接解构arr1,实际传参1, 1, 1, 1, 1, 1, 1, 1, 1, 1
let arr6 = Array.of(...arr1);
// ES6: Array.from(),基于其他对象创建新数组
let arr7 = Array.from("1111111111", (val) => parseInt(val));

@veneno-o
Copy link
Contributor

// 补充一个
"1".repeat(10).split("")

@kangkang123269
Copy link

kangkang123269 commented Sep 11, 2023

  1. 使用Array构造函数和fill()方法:
var arr = new Array(10).fill(1);
  1. 使用循环:
var arr = [];
for (let i = 0; i < 10; i++) {
    arr.push(1);
}
  1. 使用Array.from()方法:
var arr = Array.from({length: 10}, () => 1);
  1. 使用扩展运算符和fill()方法:
var arr = [...new Array(10)].map(() => 1);
  1. 字符串的repeat和split方法
var arr = "1".repeat(10).split("")

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

6 participants