Override print representation of a JavaScript array [duplicate] - javascript

This question already has answers here:
Does console.log invokes toString method of an object?
(4 answers)
How do I override the default output of an object?
(2 answers)
Closed 5 years ago.
I'm trying to take an array object and change its print representation - just of that object, not of all arrays in the program. I hoped setting the toString property would do the job, but it doesn't:
var a = [1, 2, 3]
// Prints using the default representation
console.log(a)
// Try to override toString
a.toString = function() {
return 'some new representation'
}
// Still uses the default representation
console.log(a)
What am I missing?

var a = [1, 2, 3];
// Prints using the default representation
console.log(a);
// Try to override toString
a.toString = function() {
return 'some new representation'
}
// append blank string to invoke toString function
console.log(""+a);

Related

What am I missing in this Javascript Array behavior? [duplicate]

This question already has answers here:
Array.fill(Array) creates copies by references not by value [duplicate]
(3 answers)
Array.prototype.fill() with object passes reference and not new instance
(7 answers)
Closed 9 months ago.
I tried this in the chrome dev tools console:
let a = [[null,null],[null,null]]
function na(){ return Array(2).fill(Array(2)) }
let b = na();
console.log(JSON.stringify(a))
// [[null,null],[null,null]]
console.log(JSON.stringify(b))
// [[null,null],[null,null]]
So far, so good. I was expecting both a and b with the same values and strucuture. Then I wanted to test a small function that should append an extra value in each line:
function add(x) { x.map( line => line.push(null) )}
add(a)
console.log(JSON.stringify(a))
// [[null,null,null],[null,null,null]]
add(b)
console.log(JSON.stringify(b))
// [[null,null,null,null],[null,null,null,null]]
// ?! I was not expecting this extra value here...
Well, that was unexpected.
Why is that extra null appearing in add(b) ?
function na(){
return Array(2).fill(Array(2))
}
na() fills the empty Array(2) with shallow copies of the second Array(2) object.
As a result changing values in any of the clones changes the Array's value everywhere.
a = Array(5).fill(Array(3))
a[0][0] = 1
a[0][1] = 2
a[0][2] = 3
console.log(JSON.stringify(a))
So because b has 2 elements and you are using .push() to add an element to b for each of the (same) arrays, 2 new elements are added to the array.

JavaScript array expressions return object literal in one line [duplicate]

This question already has answers here:
ECMAScript 6 arrow function that returns an object
(6 answers)
Closed 3 years ago.
Its known that someone can make a one-line array function like this to return the single value:
var func = (x) => x + 1 //func(2) == 3
and you can also make multi-line array-functions, whose values need to be manually returned:
var funcMultiline = (x) => {
var result = 1;
result += x;
return result;
}
funcMultiline(4) == 5; //true
So the question:
let's say I want to return a new object in one line, if I use the brackets, then the array-function is treated like a multi-line function, and doesn't actually return the object-literal. Is there any direct way to create an object literal in, lets say, a map function? Like:
[...Array(25)].map(e => {x: 5, y:10}) //this is a syntax error, but how can I make this work
Returning object literals using the concise body syntax params => {object:literal} will not work as expected.
You have to wrap the object literal with parenthesis:
var res = [...Array(25)].map(e => ({x: 5, y:10}))
console.log(res);

'this' keyword in built in functions [duplicate]

This question already has answers here:
What is the difference between string primitives and String objects in JavaScript?
(12 answers)
Are strings objects? [duplicate]
(6 answers)
How does the "this" keyword work, and when should it be used?
(22 answers)
Closed 4 years ago.
I don't quite understand how does the 'this' keyword in built-in functions like String, Number, etc point to the primitive value directly instead of the object like the 'this' keyword is supposed to. Is it just directly set by javascript engine?
I have this example:
String.prototype.repeatify = function(times) {
console.log(this); // Output - StringĀ {"hello"}
var str = "";
for(var i=0; i<times; i++) {
str += this; //how does 'this' gets set to 'hello' and not the object- String{ }??
}
return str;
}
var string = new String('hello');
console.log(string.repeatify(3)); //Output - prints hellohellohello
I was expecting the output in the chrome devtools to be [object Object][object Object][object Object]
There's a lot to this, but it's essentially the target of the function invocation.
Some examples:
String.prototype.whatever = function() {
return this + ' ugh.. whatever.'
// `this` is the string this method is called against
}
Array.prototype.slip = function() {
return ['Hellooo', ...this];
// `this` is the array in which the function is invoked on
}
function doSomething() {
console.log(this + ' something');
// `this` is whatever the function is bound to
}
console.log('Excuse me'.whatever()) // Excuse me ugh.. whatever.
console.log([1, 2, 3].slip()) // ["Hellooo", 1, 2, 3]
// In this case, the string 'I will do' becomes `this` in the doSomething function above as it's explicitly bound
doSomething.bind('I will do')(); // I will do something
var string = 'hello'; // ------------
// this refers to the |
// ----------v--string itself => 'hello'
console.log(string.repeatify(3));
You're defining repeatify on String prototype so this is just a type of String. Thus, it will log hellohellohello.

Using a string to return a variable [duplicate]

This question already has answers here:
How to find JavaScript variable by its name
(7 answers)
Closed 8 years ago.
I'm trying to find a way of using a string to refer to a variable.
Here is an example using jQuery:
var array = [1,2,3];
$('.array').click(function(){
var foo = $(this).attr('class');
return foo[1];
});
I want this to return the number '2' -
but as foo is a string it will return the sub string 'r'.
edit - the answer I was looking for was:
var array = [1,2,3];
$('.array').click(function(){
var foo = $(this).attr('class');
return eval(foo)[1];
});
I don't know if this is quite what you mean, but a Javascript object can do this.:
foo = {}; // create object
foo["string"] = [1,2,3]; // now the list [1,2,3] can be referenced
// by foo.string, or foo["string"]
console.log(foo["string"][1]); // Output with string.
Is that what you mean?

function(&param) - like in PHP [duplicate]

This question already has answers here:
Closed 11 years ago.
Possible Duplicate:
JavaScript Pass Variables Through Reference
How can you do something like this in javascript?
In PHP you can put a & in a function in front of the parameter to write directly back to the variable.. How can you do something like this in javascript?
In JavaScript, values are passed to functions by value. Objects, however, are passed by reference.
Passing values:
function myfunction(x)
{
// x is equal to 4
x = 5;
// x is now equal to 5
}
var x = 4;
alert(x); // x is equal to 4
myfunction(x);
alert(x); // x is still equal to 4
Passing objects:
function myobject()
{
this.value = 5;
}
var o = new myobject();
alert(o.value); // o.value = 5
function objectchanger(fnc)
{
fnc.value = 6;
}
objectchanger(o);
alert(o.value); // o.value is now equal to 6
Source: http://snook.ca/archives/javascript/javascript_pass
If you pass an object into a function it is always treated as passing a reference to it.
To have a similar effect for primitive values, you might wrap them in an object before like
var intVal = { val: 0 };
That way you can pass it to a function and still modify the actual variable.

Categories