Hi I'm debugging my page for IE8 compat mode, and this script just doesn't like to work and crushes.
Basically it had to iterate through a 3D array, and add a local path to a variable. Well I could do it otherwise, but I'm just curious why the ** it never works...
Any suggestions are welcome :) Here's the code:
for(i=0;i<menu_items_p.length;i++)
for(j=0;j<menu_items_p[i].length;j++)
menu_items_p[i][j][1]='http://127.0.0.1/'+menu_items_p[i][j][1];
and the array looks something like this:
var menu_items_p =
[
[ //Products
['Health Care', 'products/health.php'],
['Aroma Therapy','products/scents.php'],
],
[ // Empty
],
[ //Test
['What ever', 'spirulina/about.php'],
]
]
The problem though is that it sometimes have empty values, and array.length triggers some error...
When used your original array declaration:
var menu_items_p =
[
[ //Products
['Health Care', 'products/health.php'],
['Aroma Therapy','products/scents.php'],
],
[ // Empty
],
[ //Test
['What ever', 'spirulina/about.php'],
]
]
error occurs in IE8 but not in IE9. Just remove two commas:
var menu_items_p =
[
[ //Products
['Health Care', 'products/health.php'],
['Aroma Therapy','products/scents.php'] // here comma removed
],
[ // Empty
],
[ //Test
['What ever', 'spirulina/about.php'] // here comma removed
]
]
and all must work fine.
Maybe your code could handle empty values this way:
for(var i = 0; i < menu_items_p.length; i++) {
// we skip the value if it is empty or an empty array
if(!menu_items_p[i] || !menu_items_p[i].length) continue;
for(var j = 0; j < menu_items_p[i].length; j++) {
// again, we skip the value if it is empty or an empty array
if(!menu_items_p[i][j] || !menu_items_p[i][j].length) continue;
menu_items_p[i][j][1] = 'http://127.0.0.1/' + menu_items_p[i][j][1];
}
}
AS suggested by Yoshi and ThiefMaster, I made it following, and this is what solved it:
for(var i=0;i<menu_items_p.length;i++)
if (menu_items_p[i] !== undefined)
for(var j=0;j<menu_items_p[i].length;j++)
if (menu_items_p[i][j] !== undefined)
menu_items_p[i][j][1]='http://127.0.0.1/'+menu_items_p[i][j][1];
Global vars replaced.
Check for undefined.
It's a pity they didn't answer in a formal way, so I would have to answer my self :)
Thanks everyone!
Related
I'm trying to add values into 2D array based on the position that is present in the input data.
For example, the below format represents 0 as row, 0 as column and 5 is length of the value.
[
"0,0,5",
"hello"
],
How do I insert the values into 2D array based on position like [0][0], [0][1] and [0][2]?
Except from my code
const data = [
[
"0,0,5",
"hello"
],
[
"0,1,10",
"js is fun!"
],
[
"0,2,0",
""
]
]
let array2D = [
[]
];
let i = 0
for (let r = 0; r < data.length; ++r) {
array2D[r] = [];
for (let c = 0; c < data.length; ++c) {
array2D[r][c] = data[i++];
}
}
console.log(array2D);
Ok, thank you for your input.. it means that I'll just make a function to place into an array with 4 arguments.. col,row,arr&data
//important function
function place2d(row,col,arr,data){
//row col logic works like arr[row][col]
arr[row]=arr[row]||[]
arr[row][col]=data
}
var array2dArray=[]
//this loop would take the data array and place the entire index in the desired destination
data.forEach(a=>{
var [row,col]=a[0].split(',')
place2d(row,col,array2dArray,a) //the data to put into each part of the 2d array would an array itself(like data[0])
})
console.log(array2dArray)
//but I might just wanna put the text in the 2d array
var text2dArray=[]
data.forEach(a=>{
var [row,col]=a[0].split(',')
place2d(row,col,text2dArray,a[1]) //the data to be put in each part of the 2d array would be the a text variable(like data[0][1] is "hello")
})
console.log(text2dArray)
<script>
//sry it just takes space in the js part that's unnessecary
window.data = [
[
"0,0,5",
"hello"
],
[
"0,1,10",
"js is fun!"
],
[
"0,2,0",
""
]
]
</script>
With this function, you can take an empty array, place row 10 col 4 in empty array putting any data like 'xD' and it will work out eg: try place2d(10,4,emptyArrName,"xD") and it works.. just one thing to note..
IT ONLY APPLIES array structures to WHERE IT NEEDS TO.. doing things like the example above would leave a lot of undefined slots.. wild example below
//now for a wild example to show that the function works
window.data2=[
["text for [10][0]","0/10"],
["text for [2][5]","5/2"]
]
//don't forget the placer function :D
function place2d(row,col,arr,data){
//row col logic works like arr[row][col]
arr[row]=arr[row]||[]
arr[row][col]=data
}
//at the end of the day, all I'm changing is the information I make out of the array in the forEach loops in order to simply place in the function
var finalArray=[]
place2d(3,4,finalArray,"randomDataThatCouldBe_ANYTHING_notJustText")
data2.forEach(a=>{
var [col,row]=a[1].split('/')
place2d(row,col,finalArray,a[0])
})
console.log(finalArray)
I have been trying to use the unshift function with a MD array, and I cannot get it to work accordingly.
I am using shift okay and it does what is needed like expected but unshift does not.
Below is the array which I am using:
[ [ '487', 'RINGING' ], [ '477', 'RINGING' ] ]
When I try and do an unshift on it it displays the following:
[ [ '487', 'RINGING' ], [ '477', 'RINGING' ], 2 ]
I simply need to move 477 array to the beginning like so:
[ [ '477', 'RINGING' ], [ '487', 'RINGING' ]]
The code I am using:
var channelArrStatus = [ [ '477', 'RINGING' ], [ '487', 'RINGING' ]];
function monitor_channel(event, channel) {
if (event.device_state['state'] === "RINGING") {
var name = "User_487";
var status = "NOT_INUSE"
var index = 0;
if (channelArrStatus.length === 0) {
var chanar = new Array(name, status);
channelArrStatus.push(chanar);
} else {
var found = false;
for (var i in channelArrStatus) {
var channelArrStatusElem = channelArrStatus[i];
if (channelArrStatusElem[0] === name) {
index = i;
found = true;
if (channelArrStatus[index][1] !== "DND") {
channelArrStatus.push(channelArrStatus.unshift());
setTimeout(function () {
channelArrStatus[index][1] = status;
}, 10000);
}
}
}
}
}
I cant get it to move an array to the beginning of the array as highlight above using unshift.
Any suggestions?
EDIT:JSFiddle
The call .unshift() prepends nothing and returns the length of the array - 2 in your case - and that's the value you are pushing.
You either want
channelArrStatus.push(channelArrStatus.shift()); // no un-
or
channelArrStatus.unshift(channelArrStatus.pop());
That said, you should use literal notation instead of the Array constructor and avoid for in enumerations on arrays.
On this line
channelArrStatus.push(channelArrStatus.unshift());
You are adding the length of array to the end of the array.
If you want to add an element to the start of array, just call unshift.
channelArrStatus.unshift(element);
I'm rewriting some Python code in javascript and I'm running into something strange. I'm sure I'm overlooking something stupid, but it appears that it's returning a comma-separated string where I expect an array.
python:
triples = [('one', 'two', 'three'), (...), ... ]
for w1, w2, w3 in triples:
key = (w1, w2)
if key in self.cache:
self.cache[key].append(w3)
else:
self.cache[key] = [w3]
returns:
('of', 'Thee,'): ['Sailing', 'Light'],
('meat', 'within'): ['is'],
javascript:
for (var i=0; i<=triples.length; i++) {
if (triples[i]) {
var key = [triples[i][0], triples[i][1]];
if (key in this.cache) {
this.cache[key].push(triples[i][2]);
} else {
this.cache[key] = [];
this.cache[key].push(triples[i][2]);
}
}
}
returns:
'you,estimated,': [ 'and', 'and' ],
'estimated,,and': [ 'far', 'far' ],
Still learning... sorry if this doesn't make sense or sounds stupid :P
I have 2 variables "timestamps" and "clicks" and a string of numbers:
{
"timestamps":[
1362096000000,1362355200000,1362441600000,1362528000000
],
"clicks":[
[
1,2,3,4
]
};
What would be the easiest way to reformat the string and output into an array like this:
[1362096000000,1],
[1362355200000,2],
[1362441600000,3],
[1362528000000,4],
Just based on the limited information you've given us, and assuming the constraints of both timestamps and clicks always being the same length of arrays, and that you want the output to be an array this will create the new desired format.
var output = [];
for (var i = 0, l = obj.timestamps.length; i < l; i++) {
output.push([obj.timestamps[i], obj.clicks[i]]);
}
/*output is now [
[1362096000000,1],
[1362355200000,2],
[1362441600000,3],
[1362528000000,4]
]*/
I have seen some of the posts for converting json to csv
for example 'http://jsfiddle.net/FLR4v/'.
I could not make them to convert this json to csv .
Here is my code (this works well but does not work with commented out var json3 below)
<html>
<head>
<title>JSON to CSV</title>
<script src="json.js" type="text/javascript"></script>
<script type="text/javascript">
//var json3 = { "inp1:val1": { "data": [ [ 1378267200000, 0.0743 ], [ 1378270800000, 0.1787 ] ] }}
var json3 = { "data": [ [ 1378267200000, 0.0743 ], [ 1378270800000, 0.1787 ], ] }
DownloadJSON2CSV(json3.data);
function DownloadJSON2CSV(objArray)
{
var array = typeof objArray != 'object' ? JSON.parse(objArray) : objArray;
var str = '';
for (var i = 0; i < array.length; i++) {
var line = '';
for (var index in array[i]) {
line += array[i][index] + ',';
}
// Here is an example where you would wrap the values in double quotes
// for (var index in array[i]) {
// line += '"' + array[i][index] + '",';
// }
line.slice(0,line.Length-1);
str += line + '\r\n';
}
window.open( "data:text/csv;charset=utf-8," + escape(str))
}
</script>
</head>
<body>
<h1>This page does nothing....</h1>
</body>
</html>
The above code works ok.
What I need is the above needs to work with the below
var json3 = { "inp1:val1": { "data": [ [ 1378267200000, 0.0743 ], [ 1378270800000, 0.1787 ] ] }}
Thanks for your help
You still haven't explained clearly what your desired output is ("CSV" is too vague, especially when your original jsfiddle produced semicolon separated output).
But you do seem to be saying that your code works if you take this object:
var json3 = { "data": [ [ 1378267200000, 0.0743 ], [ 1378270800000, 0.1787 ], ] }
...as input to your function as follows:
DownloadJSON2CSV(json3.data);
But now you want to deal with an input object that has a slightly different structure, essentially the same thing but with an extra "wrapping" layer around your original structure:
var json3 = { "inp1:val1": { "data": [ [ 1378267200000, 0.0743 ], [ 1378270800000, 0.1787 ] ] }}
If I've summed up your question accurately, here's what you need:
DownloadJSON2CSV(json3["inp1:val1"].data);
This calls your function passing the array of arrays referenced by the "data" property of the object referenced by the "inp1:val1" property of the outermost object.
(Note that what you are calling "json" is not json at all, it is an object that happens to be created using JS's object literal syntax.)
Homework for you: read the MDN article Working With Objects.