The idea is that now I have an original array, let’s say
[1,2,3,4,5]
and I want to add in new element: ["a"]
why is the code below not working?
function add(new_element){
let arr = [1,2,3,4,5];
for(let i=0;i<arr.length;i++)
{
arr.push(new_element);
}
return arr;
}
console.log(add("a"));
Did I just created a code snippet that will run indefinitely? hence exceeding the memory limit??
This is the error I get when trying to execute this code using node.
<--- Last few GCs --->
[63372:0x102801000] 2645 ms: Mark-sweep 667.2 (674.8) -> 667.2 (674.8) MB, 196.6 / 0.0 ms allocation failure GC in old space requested
[63372:0x102801000] 2848 ms: Mark-sweep 667.2 (674.8) -> 667.2 (671.8) MB, 203.2 / 0.0 ms last resort GC in old space requested
[63372:0x102801000] 3044 ms: Mark-sweep 667.2 (671.8) -> 667.2 (671.8) MB, 196.2 / 0.0 ms last resort GC in old space requested
<--- JS stacktrace --->
==== JS stack trace =========================================
Security context: 0x19d80bc25879 <JSObject>
1: add [/Users/zhouxiang/Desktop/JS/sublime.js:~1] [pc=0x2078c0a86c09](this=0x19d822f8c209 <JSGlobal Object>,new_element=0x19d875e883a9 <String[1]: a>)
2: /* anonymous */ [/Users/zhouxiang/Desktop/JS/sublime.js:11] [bytecode=0x19d83ab56879 offset=22](this=0x19d875ece889 <Object map = 0x19d8a40023b9>,exports=0x19d875ece889 <Object map = 0x19d8a40023b9>,require=0x19d875ece841 <JSFunction r...
FATAL ERROR: CALL_AND_RETRY_LAST Allocation failed - JavaScript heap out of memory
1: node::Abort() [/usr/local/bin/node]
2: node::FatalException(v8::Isolate*, v8::Local<v8::Value>, v8::Local<v8::Message>) [/usr/local/bin/node]
3: v8::internal::V8::FatalProcessOutOfMemory(char const*, bool) [/usr/local/bin/node]
4: v8::internal::Factory::NewUninitializedFixedArray(int) [/usr/local/bin/node]
5: v8::internal::(anonymous namespace)::ElementsAccessorBase<v8::internal::(anonymous namespace)::FastPackedObjectElementsAccessor, v8::internal::(anonymous namespace)::ElementsKindTraits<(v8::internal::ElementsKind)2> >::GrowCapacity(v8::internal::Handle<v8::internal::JSObject>, unsigned int) [/usr/local/bin/node]
6: v8::internal::Runtime_GrowArrayElements(int, v8::internal::Object**, v8::internal::Isolate*) [/usr/local/bin/node]
7: 0x2078c09042fd
[Finished in 3.1s with exit code -6]
[cmd: ['/usr/local/bin/node', '/Users/zhouxiang/Desktop/JS/sublime.js']]
[dir: /Users/zhouxiang/Desktop/JS]
[path: /usr/local/bin:/usr/bin:/bin:/usr/sbin:/sbin:/usr/local/share/dotnet:~/.dotnet/tools:/Library/Frameworks/Mono.framework/Versions/Current/Commands:/Applications/Xamarin Workbooks.app/Contents/SharedSupport/path-bin]