JavaScript Array.shift not working - javascript

I have been programming a system that is supposed to delete the first index of an array. Instead of changing an array from (i.e) "1,2,3,4,5" to "2,3,4,5" the console gives an error: "Uncaught TypeError: num.splice is not a function". I have heard that num.splice is not a function, it is an operation (or something) to delete the first indexed value of the array. I am confused that when I use an example code from w3Schools, there is no outputted error in the console. I don't understand why this happens.
(I have given the entire code just in case it has to do with syntax issues)
function dCrypt() {
var num = document.getElementById("demoin").value; // ex: a127
var key = ["a","b","c","d","e","f","g","h","i","j","k","l","m","n","o","p","q","r","s","t","u","v","w","x","y","z"];
var mod = 0;
var out = 0;
var prep = 0;
var pre = 0;
num.split("");
mod = num[0];
pre = key.indexOf(mod);
num.splice(0,1);
for (i=0;i <= pre;i++) {
prep += 26;
}
out = Math.floor(num + pre);
document.getElementById("demoout").innerHTML = out;
}
Thanks in advance!

When you split 'num' you have to reassign it
num = num.split("");

Referring to your link from w3schools:
The splice() method adds/removes items to/from an array, and returns the removed item(s).
As you can see the var num is string(and not an array) and has the value of the element with id demoin.
Since you are trying to splice a string and not an array. The error shows up in the console.
Solution:
Either store the value of your split in an array(it could be num itself) and then splice that array.
num = num.split("");
...
num.splice(0,1);

Related

How do I convert a JSON string object value to an integer?

I'm tring to convert a JSON object value to an integer and calculate.
It shows representativeRow.DTA_VAL well but the value of total shows NaN.
I don't think this works because the other code works well.
datav= Number(representativeRow.DTA_VAL);
this is my code
var rows = resp.Sttsapitbldata[1].row;
if (rows) {
var representativeRow;
for (i = 1; i < 30; i++) {
representativeRow = rows[i];
if(representativeRow.ITM_NM.substring(0,2)=="부산"){
// console.log(representativeRow.ITM_NM);
var sub =representativeRow.ITM_NM.substring(0,3);
var total;
var datav;
console.log(representativeRow.DTA_VAL);
datav= Number(representativeRow.DTA_VAL);
total+=datav;
console.log(total);
}
itemNm2 = representativeRow.ITM_NM;
dataV = representativeRow.DTA_VAL;
//console.log(itemNm2);
//console.log(dataV);
options.data.data.push({locname: itemNm2, listshrs: dataV});
}
korea = webponent.visual.korea.init($(".korea"), style, options);
}
See JSON file code below.
{"Sttsapitbldata":[{"head":[{"list_total_count":88},{"RESULT":{"CODE":"INFO-000","MESSAGE":"정상 처리되었습니다."}}]},{"row":[{"STATBL_ID":"T183673021266818","DTACYCLE_CD":"YY","WRTTIME_IDTFR_ID":"2016","ITM_ID":10001,"ITM_NM":"계","CLS_ID":50033,"CLS_NM":"강간","UI_NM":"명","DTA_VAL":5155,"DTA_SVAL":null},{"STATBL_ID":"T183673021266818","DTACYCLE_CD":"YY","WRTTIME_IDTFR_ID":"2016","ITM_ID":10002,"ITM_NM":"서울","CLS_ID":50033,"CLS_NM":"강간","UI_NM":"명","DTA_VAL":1129,"DTA_SVAL":null},{"STATBL_ID":"T183673021266818","DTACYCLE_CD":"YY","WRTTIME_IDTFR_ID":"2016","ITM_ID":10003,"ITM_NM":"부산","CLS_ID":50033,"CLS_NM":"강간","UI_NM":"명","DTA_VAL":314,"DTA_SVAL":null},
You should initialise total=0. You can't add to a null value on the first iteration. Although looking at it, I suspect you'd be wanting to initialise total outside of the loop

Can I assign an array value to a variable?

I can't seem to assign an array value to a variable. It always returns undefined.
In my code I have set currentWord = text[wordPos]. At the end of the code I have console logged currentWord, and text[wordPos]. My thinking says that they should return the same value, but they don't. currentWord returns undefined, and text[wordPos] returns the correct value (the first word in the 'text' array).
Solved. I had mistakenly forgot that I had 2 arrays, and thought the text array was not empty, but it was. The words array is the array I had filled in separate file.
var text = Array();
var wordPos = 0;
var currentWord = text[wordPos];
function gen() {
text = [];
var random;
for (var i = 0; i < 10; i++) {
random = words[Math.floor(Math.random() * 50)];
text.push(random);
}
document.getElementById('text').innerHTML = text.join(" ");
console.log(currentWord);
console.log(text[wordPos]);
}
Currentwork is undefined because you create an array object but never push a value into it. It transfers the current value of the variable not the reference.
There is no value at index 0 of text. If you assign some values to the text array you should be good!
Updated:
Read the OP's note above about the two arrays in the original example. In light of this information, the following script simulates an imported array words of 50 distinct values in order to generate a text of ten space-delimited numbers and indicate its first value:
// simulating an array imported from a separate file
var words = [1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31,32,33,34,35,36,37,38,39,40,41,42,43,44,45,46,47,48,49,50];
function gen() {
var wordPos = 0;
var currentWord = "";
var arr = [];
var randomVal;
var d = document;
d.g = d.getElementById;
var pText = d.g('text');
// get each of 10 values by randomly selecting an element's key
for (var i = 0; i < 10; i++) {
randomVal = words[ Math.floor( Math.random() * 50 ) ];
arr.push( randomVal );
}
pText.innerHTML = arr.join(" ");
currentWord = arr[wordPos];
console.log("Current word: ",currentWord );
}
gen();
<p id="text"></p>
This script randomly selects 10 numbers and adds them to an empty array by means of variable randomVal. This variable acquires a value in each iteration of the for-loop, during which the variable is passed to the push() method of arr in order to append it to the array. Once the loop terminates, the script joins the elements of arr on a blank space character, which yields a string whose numeric values are space-delimited.
One can discern that the script is working correctly when the console.log statement displays the first numeric value appearing in the text.

Getting error .append is not a function

I am trying to split up a string on /* and then to split up those segments on */
So that I can separate out all of the comments as I want this code to be able to take all of the comments out of the string and then put it back together.
The problem is though I keep getting this .append error which I am pretty sure is because I have made a silly syntax error but I am struggling to find it and any help would be greatly appreciated.
JS
contents = "if for /* else */ . = == === /* return */ function"
var start = /\/\*/gi;
var end = /\*\//gi;
var commentsRemovedSec2 = [];
var commentsRemovedSec1 = contents.split(start);
console.log(commentsRemovedSec1);
for (var i = 0; i < commentsRemovedSec1.length; i++) {
var z = ""
var x = commentsRemovedSec1[i]
var y = x.split(start)
z = y[0]
commentsRemovedSec2.append(z);
};
console.log(commentsRemovedSec2);
Unfortunately .append() isn't an Array method.
Instead use the Array method .push().
commentsRemovedSec2.push(z)
The push() method adds one or more elements to the end of an array and
returns the new length of the array. MDN

My java script array doesn't have a length

I have the following code:
//Populate inputData with the values of the input text boxes, in order
var inputData = {};
var x = document.getElementById("newInventoryForm");
//Added this following line in the edit
$('#additionalContent').append("My x.length property " + x.length + "<br/>");
for (var i = 0; i < x.length - 1; i++) {// -1 so we don't get the submit button
var addData = {
id : x[i].id,
value : x[i].value
};
inputData[i] = addData;
$('#additionalContent').append(inputData[i].id + " : " + inputData[i].value + "<br/>");
}
I'm attempting to pass the form data from a previously made form to another javascript function. Before I do that I have tried to make it all work in the same .js page, however when I try to output my inputData through a for loop, it shows up blank. I determined this is because inputData.length is undefined. I was under the impression that declaring it as inputData = {}; made it an array and thus had a default length value. How can I change this to have the correct length?
Edit
Several commenters have said that var x = document.getElementById("newInventoryForm"); should return null or a node, neither of which has a length property. Adding the line in the code above, has produced this output.
My x.length property 18
serialNumber : 456
someDatafield : someInput
You've declared it as an object.
Perhaps var inputData = []; will give you better results.
{} is an object, not an array.
You want [].
Also, getElementById() does not return an array; your entire code makes no sense.

won't loop array javascript

Why cant i access my array?
function map(array){
for(i=0; i <=array.length; i++){
var location=array[i].location;
console.log("loc"+location);
var user = array[i].from_user;
console.log("user"+user);
var date = array[i].created_at;
var profile_img = array[i].profile_img;
var text = array[i].text;
var contentString = text;
//geocode(user,date, profile_img, text, contentString,location);
}
}
It gives me undefined for every element.I want to access it and pass the variables to the geocode function.
data structure:
array=[{user: a,user_id: b,date: c,profile_img: d,text: e,contentString: f,url:
g,location:o},{user: a,user_id: b,date: c,profile_img: d,text: e,contentString:
f,url:g,location:o},{user: a,user_id: b,date: c,profile_img: d,text:
e,contentString: f,url: g,location:s}];
dont worry about the values..!
I forgot to mention when i first made the post(question). the location of the array is inserted in the previous function whereas the array didn't include the attribute location from previous functions
When calling the function, use the object literal construct enclosed in an array literal, otherwise all values will be returned as undefined. This is how you should call your function:
map([{ // array literal enclosing an object literal
location : 1,
from_user : 2,
created_at : 3,
profile_img: 4,
text : 5
}]);
Moreover, in your loop, change:
for (i = 0; i <= array.length; i++ ) ...
...to
for (var i = 0; i < array.length; i++) ...
If you have a pre-defined array, name it and pass it to the function like this:
map(arrayObj)
If the array you pass in has a length of 0, the way you're looping it is going to try and access the list element at 0, which is going to be undefined.
However, regardless of the contents of your array, this line will always cause you trouble:
for(i=0; i <=array.length; i++)
When check the length property of your array, it is telling you the number of elements in the array. Since arrays use 0 based indexing, you're going to overrun the bounds of your array with this loop everytime.
var myArray = [1, 2, 3];
myArrary[0]; // This is 1
myArray[2]; // This is 3
Since you are looping between 0 and the length of the array, which happens to be 3, the last element you attempt to access will no exist.
myArray[3]; // Undefined
You need to check i < array.length rather than i <= array.length.
Your code is fine. With the provided input and function you get this:
loco
userundefined
loco
userundefined
locs
userundefined
The reason every user is coming up as undefined is because of:
var user = array[i].from_user;
console.log("user"+user);
The objects you are passing in do not have a from_user property, so naturally it comes up as undefined. Maybe you meant array[i].user_id?
Also, as Aesthete pointed out, you're running outside the bounds of your array because of the way you're checking for length. Do this instead:
for(var i = 0, n = array.length; i < n; i++) {
// your code in here
}
Notice that I preface i with var so it does not become an implicit global. Also, I declare a second variable n so that you only need to access array.length once. This is common practice.
So, putting it all together:
function map(array){
for(var i = 0, n = array.length; i < n; i++){
var location=array[i].location;
console.log("loc"+location);
var user = array[i].user_id;
console.log("user"+user);
var date = array[i].created_at;
var profile_img = array[i].profile_img;
var text = array[i].text;
var contentString = text;
//geocode(user,date, profile_img, text, contentString,location);
}
}
array=[{user: 'a',user_id: 'b',date: 'c',profile_img: 'd',text: 'e',contentString: 'f',url:
'g',location:'o'},{user: 'a',user_id: 'b',date: 'c',profile_img: 'd',text: 'e',contentString:
'f',url:'g',location:'o'},{user: 'a',user_id: 'b',date: 'c',profile_img: 'd',text:
'e',contentString: 'f',url: 'g',location:'s'}];
map(array);
Notice I changed your object properties to strings - this is because you did not give values for these, but you probably don't want to do this. Output is:
loco
userb
loco
userb
locs
userb
All is well. If you are still getting undefined for location then your error must lie with the o property of the objects you're passing in.

Categories

Resources