Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
231 views
in Technique[技术] by (71.8m points)

javascript - 需要JavaScript Collections.js时,JavaScript中的Array.from无法正常工作(Array.from in javascript not working when requiring JavaScript Collections.js)

I'm trying to learn to use Array.from, as I really don't like calling fill and then map

(我正在尝试学习使用Array.from,因为我真的不喜欢先调用fill然后映射)

For example I'm converting

(例如我正在转换)

const tasks = 3
const graph = Array(tasks).fill(0).map(() => Array())

into

(进入)

const graph = Array.from(Array(tasks), () => new Array())

but I get the following error

(但我收到以下错误)

graph[1].push(1)
        ^
TypeError: Cannot read property 'push' of undefined

I saw on another thread someone post

(我在另一个帖子上看到有人发帖)

var arr = Array.from(Array(2), () => new Array(4));
arr[0][0] = 'foo';
console.info(arr);

And this too throws

(这也抛出)

arr[0][0] = 'foo';
          ^
TypeError: Cannot set property '0' of undefined

After testing line by line, it appears this line breaks it

(逐行测试后,似乎此行将其中断)

const Deque = require('collections/deque')

Any ideas why https://www.collectionsjs.com breaks the array.from() behavior?

(为什么https://www.collectionsjs.com会破坏array.from()行为?)

  ask by FaultyJuggler translate from so

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

As people are saying in the comments, your code works.

(正如人们在评论中所说的那样,您的代码有效。)

I'm only adding it as an answer to include this code snippet so that you can see for yourself.

(我仅将其添加为包括此代码段的答案,以便您可以自己查看。)

I imagine the problem is to do with where you're calling graph[1].push(1) .

(我想象问题出在哪里调用了graph[1].push(1) 。)

I suspect it's being called from somewhere that doesn't have access to graph .

(我怀疑它是从无法访问graph地方调用的。)

The minimal version presented below works, so you need to find the minimal version of your code that causes the error, and you'll probably find the answer in the process

(下面介绍的最低版本有效,因此您需要查找导致错误的代码的最低版本,您可能会在此过程中找到答案)

 const tasks = 3 const graph = Array.from(Array(tasks), () => new Array()) graph[1].push(1); console.log(graph) 


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...