简体   繁体   中英

Javascript: array.push is undefined

I have my code:

var name = [];
var mark1 = [];
var mark2 = [];
var mark3 = [];
var total = [];
count = 0
count2 = 0
var i = 0;
while (count != 2) {
  var nam = prompt("Enter name:")
  name.push(nam);
  var mk1 = prompt("Enter mark 1:");
  var mk1 = parseInt(mk1);
  mark1.push(mk1);
  var mk2 = prompt("Enter mark 2:");
  var mk2 = parseInt(mk2);
  mark2.push(mk2);
  var mk3 = prompt("Enter mark 2:");
  var mk3 = parseInt(mk3);
  mark3.push(mk3);
  var tot = mk1 + mk2 + mk3;
  total.push(tot)
  count = count + 1
  console.log(mk1 + mk2 + mk3);
  console.log(nam);
  console.log("the count is " + count)
};

When I run it I get an error:

Uncaught TypeError: undefined is not a function

on Line 12 which is name.push(nam);

I have looked around but I am not sure what I am doing wrong. Help appreciated.

This is an interesting one. It all boils down to an unfortunate choice of variable name. Unfortunately name is a property of the window object. When you refer to name you are actually referring to window.name, not the array called name . If you rename name to something else, it should work just fine.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM