Reputation: 47
So lets say I have a log in google's console like this
[[296,279],[304,280],[308,280],[312,280]]
from my script here below
evtSource.onmessage = function(e) {
var obj = JSON.parse(e.data);
var line = JSON.stringify(obj.line)
var size = JSON.stringify(obj.lineWidth)
var color = JSON.stringify(obj.lineColor) // Not needed, but defined anyways.
var chat = JSON.stringify(obj.msg)
if (obj.ident === "") //mee
{
$.post("/draw.php?ing=_index", {
l: (line),
w : parseInt(obj.lineWidth) + 2,
c: ("ffffff"),
o: ("100"),
f: ("1"),
_: ("false")
})
console.log(line) //Logs the line. (Example in question.)
How could I add a value of 20 to each item in the array when it logs. So it will log something like this
[[316,299],[324,300],[328,300],[332,300]]
and not like this (The original.)
[[296,279],[304,280],[308,280],[312,280]]
Upvotes: 1
Views: 71
Reputation: 7325
If you want to print the array with altered data but without altering the original you probably want to use JSON.stringify
and JSON.parse
to copy the array.
JSON.stringify
also accepts a second parameter that allows you to edit the values while the object is being stringified.
var original = [
[296, 279],
[304, 280],
[308, 280],
[312, 280],
[[58, 60], [75, 84]],
4,
[[5, 9], [[0], [-3]], 8]
];
var json = JSON.stringify(original, function(key, value) {
return typeof value === "number" ? value + 20 : value;
});
console.log(json);
console.log(JSON.parse(json));
This will work, regardless of how many dimensions the array has (and is ES5 compatible).
Upvotes: 0
Reputation: 4330
You can use Array.map function.
Here we provide a function which will be executed with each element of the array. Which in your case will be another map
function.
const line = [[296, 279],[304, 280],[308, 280],[312, 280]]
const out = line.map(arr => arr.map(x => x + 20))
console.log(out)
Upvotes: 0
Reputation: 44145
Use map
:
const arr = [
[296, 279],
[304, 280],
[308, 280],
[312, 280]
];
const res = arr.map(e => e.map(f => f + 20));
console.log(res);
.as-console-wrapper {
max-height: 100% !important;
top: auto;
}
Upvotes: 4