问:
Get index of clicked element
So I'm still pretty new at JavaScript, I can do some basic stuff, but a lot of it, not so much. Anyway I am trying to create a gallery that opens a larger slideshow when one of the elements is clicked. The problem I'm running into is I don't know how to find the index of the clicked elements. I've tried Google, and I even looked here and lots of answers to the question, but none of them seem to work for my bit of code.

```<code>    var getThumbs = Array.from(document.querySelectorAll('.retail-thumbnail'));
    for (var i = 0; i < getThumbs.length; i++) {
        getThumbs[i].onclick = function(e) {
            var createSlideshow = document.createElement('div');
            createSlideshow.setAttribute('class', 'retail-slideshow');
            var createClsBtn = document.createElement('div');
            createClsBtn.setAttribute('class', 'close');
            createClsBtn.innerHTML = '×';
            createSlideshow.append(createClsBtn);
            var slides = '';
            const index = getThumbs
            getThumbs.forEach(gall => {
                if (gall.classList.contains('video-thumb')) {
                    gall.childNodes.forEach(source => {
                            source = Array.from(source.src.split('.'));
                            source = source[source.length - 3];
                            slides += '<div class="retail-slide">\n' +
                                      '<iframe src="https://player.vimeo.com/video/' + source + '" width="100%" height="100%" frameborder="0" webkitallowfullscreen mozallowfullscreen></iframe>\n' +
                                      '</div>\n\n'
                    });
                } else {
                    slides += '<img src="' + gall.src + '" class="retail-slide">\n\n'
                }
            });
            slides += '<div id="retail_ss_prev"></div><div id="retail_ss_next"></div>';
            createSlideshow.innerHTML += slides;
            var activeModal = document.querySelector('.modal.active');
            activeModal.append(createSlideshow);
            var activeCls = document.querySelector('.retail-slideshow > .close');
            activeCls.addEventListener('click', function(e) {
                activeCls.parentNode.remove();
            });
        };
    };
};
</code>```

So this is what I have, and it writes everything, but I can't get the index when I click on one of the .retail-thumbnail elements. Any help is greatly appreciated. Preferably in Vanilla JS. I try to stay away from Jquery

答:
You can take advantage of closures.

```<code>var getThumbs = Array.from(document.querySelectorAll('.retail-thumbnail'));
for (var i = 0; i < getThumbs.length; i++) {
    getThumbs[i].onclick = function(index) {
        return function(e) {
            //Your current function, where index now is the same as i at the moment of assigning the event listener
        };
    }(i);
}
</code>```

Or, you could add a data attribute to each element, either in the html (something like data-index="1"), or setting them from js:

```<code>var getThumbs = Array.from(document.querySelectorAll('.retail-thumbnail'));
for (var i = 0; i < getThumbs.length; i++) {
    getThumbs[i].dataset.index=i;
    getThumbs[i].onclick = function(e) {
        var index=this.dataset.index;
        //....
    };
}
</code>```

Title: Get index of clicked element

Body:
So I'm still pretty new at JavaScript, I can do some basic stuff, but a lot of it, not so much. Anyway I am trying to create a gallery that opens a larger slideshow when one of the elements is clicked. The problem I'm running into is I don't know how to find the index of the clicked elements. I've tried Google, and I even looked here and lots of answers to the question, but none of them seem to work for my bit of code.

    var getThumbs = Array.from(document.querySelectorAll('.retail-thumbnail'));
    for (var i = 0; i < getThumbs.length; i++) {
        getThumbs[i].onclick = function(e) {
            var createSlideshow = document.createElement('div');
            createSlideshow.setAttribute('class', 'retail-slideshow');
            var createClsBtn = document.createElement('div');
            createClsBtn.setAttribute('class', 'close');
            createClsBtn.innerHTML = '×';
            createSlideshow.append(createClsBtn);
            var slides = '';
            const index = getThumbs
            getThumbs.forEach(gall => {
                if (gall.classList.contains('video-thumb')) {
                    gall.childNodes.forEach(source => {
                            source = Array.from(source.src.split('.'));
                            source = source[source.length - 3];
                            slides += '
\n' +
                                      '\n' +
                                      '
\n\n'
                    });
                } else {
                    slides += '\n\n'
                }
            });
            slides += '

';
            createSlideshow.innerHTML += slides;
            var activeModal = document.querySelector('.modal.active');
            activeModal.append(createSlideshow);
            var activeCls = document.querySelector('.retail-slideshow > .close');
            activeCls.addEventListener('click', function(e) {
                activeCls.parentNode.remove();
            });
        };
    };
};

So this is what I have, and it writes everything, but I can't get the index when I click on one of the .retail-thumbnail elements. Any help is greatly appreciated. Preferably in Vanilla JS. I try to stay away from Jquery

Body:
You can take advantage of closures.

var getThumbs = Array.from(document.querySelectorAll('.retail-thumbnail'));
for (var i = 0; i < getThumbs.length; i++) {
    getThumbs[i].onclick = function(index) {
        return function(e) {
            //Your current function, where index now is the same as i at the moment of assigning the event listener
        };
    }(i);
}

Or, you could add a data attribute to each element, either in the html (something like data-index="1"), or setting them from js:

var getThumbs = Array.from(document.querySelectorAll('.retail-thumbnail'));
for (var i = 0; i < getThumbs.length; i++) {
    getThumbs[i].dataset.index=i;
    getThumbs[i].onclick = function(e) {
        var index=this.dataset.index;
        //....
    };
}


来源: stackexchange

问:
Why is onclick for the first button in a form triggered when I hit ENTER key (and no keyCode in event)?
Why is onclick for the first button in a form triggered when I hit ENTER key? I am trying to figure out why onclick was triggered by the ENTER key, and then have the function go ahead if it was an actual mouse/tap button click, or have the function ignore the key press if it was the ENTER key.

I tried checking the event.keyCode (passed into javascript function), but it is undefined.

In fact the only property that seems to be set is event.isTrusted but no other properties exist.

EDIT: Created new demo code to better explain the issue I am having...

Here is js fiddle with the issue: https://jsfiddle.net/Ld142qx3/24/

When you put the cursor in the Quantity 2 input box (the second box) and you click enter, it fires the onclick event for the first LESS button in front of the Quantity 1 input box.

There is no keyCode property passed in with event to identify whether onclick was actually triggered by clicking with a mouse or triggered by ENTER key.

My original test code HTML is:

```<code><form onsubmit="return false;">
  Quantity 1: <button id="b1-less" onclick="return b1Less(this.id, event);">less</button>
  <input type="text" id="q1" value="10" size="10">
  <button id="b1-more" onclick="return b1More(this.id, event);">more</button>
  <br>
  Quantity 2: <button id="b2-less" onclick="return b2Less(this.id, event);">less</button>
  <input type="text" id="q2" value="5" size="10">
  <button id="b2-more" onclick="return b2More(this.id, event);">more</button>
</form>
</code>```

And my original javascript to go with it is:

```<code>function b1Less(_id, _event) {
  alert(_event.keyCode);
  _val = parseInt(document.getElementById('q1').value);
  _val = _val - 1;
  document.getElementById('q1').value = _val;
  return false;
}
function b1More(_id, _event) {
  _val = parseInt(document.getElementById('q1').value);
  _val = _val + 1;
  document.getElementById('q1').value = _val;
  return false;
}

function b2Less(_id, _event) {
  _val = parseInt(document.getElementById('q2').value);
  _val = _val - 1;
  document.getElementById('q2').value = _val;
  return false;
}
function b2More(_id, _event) {
  _val = parseInt(document.getElementById('q2').value);
  _val = _val + 1;
  document.getElementById('q2').value = _val;
  return false;
}
</code>```

答:
Your problem is that the type of a button inside a form defaults to a "submit" button (see the spec), and when a form is implicitly submitted (which happens when you press ENTER in an input field, the first "submit" button in the form also has its onclick event handler triggered (see the spec). Changing your buttons to have type="button" resolves the issue:

function b1Less(_id, _event) {
  _val = parseInt(document.getElementById('q1').value);
  _val = _val - 1;
  document.getElementById('q1').value = _val;
  return false;
}

function b1More(_id, _event) {
  _val = parseInt(document.getElementById('q1').value);
  _val = _val + 1;
  document.getElementById('q1').value = _val;
  return false;
}

function b2Less(_id, _event) {
  _val = parseInt(document.getElementById('q2').value);
  _val = _val - 1;
  document.getElementById('q2').value = _val;
  return false;
}

function b2More(_id, _event) {
  _val = parseInt(document.getElementById('q2').value);
  _val = _val + 1;
  document.getElementById('q2').value = _val;
  return false;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><form onsubmit="return false;">
  Quantity 1: <button type="button" id="b1-less" onclick="return b1Less(this.id, event);">less</button>
  <input type="text" id="q1" value="10" size="10">
  <button type="button" id="b1-more" onclick="return b1More(this.id, event);">more</button>
  <br> Quantity 2: <button type="button" id="b2-less" onclick="return b2Less(this.id, event);">less</button>
  <input type="text" id="q2" value="5" size="10">
  <button type="button" id="b2-more" onclick="return b2More(this.id, event);">more</button>
</form></code>```

ContentLicense: CC BY-SA 4.0

Body:
Why is onclick for the first button in a form triggered when I hit ENTER key? I am trying to figure out why onclick was triggered by the ENTER key, and then have the function go ahead if it was an actual mouse/tap button click, or have the function ignore the key press if it was the ENTER key.

I tried checking the event.keyCode (passed into javascript function), but it is undefined.

In fact the only property that seems to be set is event.isTrusted but no other properties exist.

EDIT: Created new demo code to better explain the issue I am having...

Here is js fiddle with the issue: https://jsfiddle.net/Ld142qx3/24/

When you put the cursor in the Quantity 2 input box (the second box) and you click enter, it fires the onclick event for the first LESS button in front of the Quantity 1 input box.

There is no keyCode property passed in with event to identify whether onclick was actually triggered by clicking with a mouse or triggered by ENTER key.

My original test code HTML is:

<form onsubmit="return false;">
  Quantity 1: <button id="b1-less" onclick="return b1Less(this.id, event);">less</button>
  <input type="text" id="q1" value="10" size="10">
  <button id="b1-more" onclick="return b1More(this.id, event);">more</button>

  Quantity 2: <button id="b2-less" onclick="return b2Less(this.id, event);">less</button>
  <input type="text" id="q2" value="5" size="10">
  <button id="b2-more" onclick="return b2More(this.id, event);">more</button>
</form>

And my original javascript to go with it is:

function b1Less(_id, _event) {
  alert(_event.keyCode);
  _val = parseInt(document.getElementById('q1').value);
  _val = _val - 1;
  document.getElementById('q1').value = _val;
  return false;
}
function b1More(_id, _event) {
  _val = parseInt(document.getElementById('q1').value);
  _val = _val + 1;
  document.getElementById('q1').value = _val;
  return false;
}

function b2Less(_id, _event) {
  _val = parseInt(document.getElementById('q2').value);
  _val = _val - 1;
  document.getElementById('q2').value = _val;
  return false;
}
function b2More(_id, _event) {
  _val = parseInt(document.getElementById('q2').value);
  _val = _val + 1;
  document.getElementById('q2').value = _val;
  return false;
}

Body:
Your problem is that the type of a button inside a form defaults to a "submit" button (see the spec), and when a form is implicitly submitted (which happens when you press ENTER in an input field, the first "submit" button in the form also has its onclick event handler triggered (see the spec). Changing your buttons to have type="button" resolves the issue:

function b1Less(_id, _event) {
  _val = parseInt(document.getElementById('q1').value);
  _val = _val - 1;
  document.getElementById('q1').value = _val;
  return false;
}

function b1More(_id, _event) {
  _val = parseInt(document.getElementById('q1').value);
  _val = _val + 1;
  document.getElementById('q1').value = _val;
  return false;
}

function b2Less(_id, _event) {
  _val = parseInt(document.getElementById('q2').value);
  _val = _val - 1;
  document.getElementById('q2').value = _val;
  return false;
}

function b2More(_id, _event) {
  _val = parseInt(document.getElementById('q2').value);
  _val = _val + 1;
  document.getElementById('q2').value = _val;
  return false;
}

<form onsubmit="return false;">
  Quantity 1: <button type="button" id="b1-less" onclick="return b1Less(this.id, event);">less</button>
  <input type="text" id="q1" value="10" size="10">
  <button type="button" id="b1-more" onclick="return b1More(this.id, event);">more</button>
  <br> Quantity 2: <button type="button" id="b2-less" onclick="return b2Less(this.id, event);">less</button>
  <input type="text" id="q2" value="5" size="10">
  <button type="button" id="b2-more" onclick="return b2More(this.id, event);">more</button>
</form>


问:
TypeError passing Series with dtype int to dateutil.relativedelta
I'm trying to use dateutil.relativedelta.relativedelta to add an int type pandas Series to a datetime Series.

df.loc[:,'calc_eli_date'] = (
    datetime.datetime(df['pol_eff_date'])
    + relativedelta(years=df['frt_elig_year'])
)
```

<p><code>df['pol_eff_date']</code> is <code>datetime64[ns]</code> type</p>

<p><code>df['frt_elig_year']</code> is <code>int</code> </p>

<p>But I get the following error:</p>

```TypeError: cannot convert the series to class 'int'
```

答:
The dateutil.relativedata.relativedata constructor only accepts datetime and integer arguments - not arrays or pandas objects.

Try pd.to_timedelta instead:

df['calc_eli_date'] = (
    df['pol_eff_date'] + pd.to_timedelta(df['frt_elig_year'], unit='Y')
)
```

Body:
I'm trying to use dateutil.relativedelta.relativedelta to add an int type pandas Series to a datetime Series.

df.loc[:,'calc_eli_date'] = (
    datetime.datetime(df['pol_eff_date'])
    + relativedelta(years=df['frt_elig_year'])
)

df['pol_eff_date'] is datetime64[ns] type

df['frt_elig_year'] is int

But I get the following error:

TypeError: cannot convert the series to class 'int'


问:
finding the mean of two values in the same dictionary
I have a csv file that contains this information

```<code>grade,low,high
S235,360,510
S275,370,530
S355,470,630
</code>```

I am wanting to find the difference between high and low but I don't know how to do this. I thought I could do it through numpy (np.mean) but it came up with an error.

this is the code I have written so far

```<code>#!/usr/bin/python3
import csv

csvfile = open('/home/aa408/steel.csv')
csvreader = csv.DictReader(csvfile)

print("%7s %8s %8s" % ("Grade", "Low MPa", "Max MPa") )

total = 0
count = 0

for gradeInfo in csvreader:
    print("%7s %8s %8s" % (gradeInfo["grade"], gradeInfo["low"],
                           gradeInfo["high"]) )
</code>```

答:
The following will calculate the difference between the high and low columns assuming they will only be integers.</p>

```<code>import csv

with open('/home/aa408/steel.csv') as cf:
    reader = csv.DictReader(cf)
    print(reader)
    for row in reader:
        print(int(row['high']) - int(row['low']))
</code>```

Body:
I have a csv file that contains this information

grade,low,high
S235,360,510
S275,370,530
S355,470,630

I am wanting to find the difference between high and low but I don't know how to do this. I thought I could do it through numpy (np.mean) but it came up with an error.

this is the code I have written so far

#!/usr/bin/python3
import csv

csvfile = open('/home/aa408/steel.csv')
csvreader = csv.DictReader(csvfile)

print("%7s %8s %8s" % ("Grade", "Low MPa", "Max MPa") )

total = 0
count = 0

for gradeInfo in csvreader:
    print("%7s %8s %8s" % (gradeInfo["grade"], gradeInfo["low"],
                           gradeInfo["high"]) )

Body:
The following will calculate the difference between the high and low columns assuming they will only be integers.

import csv

with open('/home/aa408/steel.csv') as cf:
    reader = csv.DictReader(cf)
    print(reader)
    for row in reader:
        print(int(row['high']) - int(row['low']))


问:
Preventing xmlhttp function from running again on keyup
So I have a keyup function that retrieves data from a MySQL table, and then displays it. However, it retrieves data again if a letter is changed.

See image below
How it currently is and In the inspector

What it should be doing is just replacing those suggestions with the new suggestions instead of adding it on to the list

EDIT: Shoaeb's solution works but not in the way he suggested.

```<code>document.getElementById('schoolListMenu').innerHTML="";
</code>```

I added that line right after the keyup function is called. This clears the content in the div and replaces it with the updated content once the user has stopped typing. If the user presses a key again it will clear the div again and append the updated results.

edit2: Updated JS Code

```<code>var timeout = null;
function getSchool(schoolType){
    if(schoolType1.classList.contains('active') || schoolType2.classList.contains('active'))
    {
        schoolNameField.onkeyup = function(e)
        {
            document.getElementById('schoolListMenu').innerHTML="";
            clearTimeout(timeout);
            timeout = setTimeout(function() {
                var query = e.target.value;
                console.log(query);
                var xmlhttp = new XMLHttpRequest();
                xmlhttp.onreadystatechange = function() {
                    if (this.readyState === 4 && this.status === 200) {
                        var schoolResult = this.responseText;
                        schoolResult = schoolResult.split("|");
                        for(var i = 0; i < schoolResult.length; i++)
                        {
                            var schoolSuggestion = document.createElement('div');
                            schoolSuggestion.id = 'schoolSuggestion'+i;
                            schoolSuggestion.className = 'item';
                            schoolSuggestion.innerText = schoolResult[i];
                            document.getElementById('schoolListMenu').appendChild(schoolSuggestion);
                        }
                    }
                };
                xmlhttp.open("GET", "scripts/schoolLookup.php?type="+schoolType+"&name="+query, true);
                xmlhttp.send();
            }, 500);
        };
    }
}
</code>```

How do I get it to replace the content instead of adding on new divs? I feel like I understand what the problem is and know what the solution is but I can't put it to words

答:
Change this line

document.getElementById('schoolListMenu').appendChild(schoolSuggestion);

to

document.getElementById('schoolListMenu').innerHTML(schoolSuggestion);

or you can clear the list before appending

document.getElementById('schoolListMenu').innerHTML="";
document.getElementById('schoolListMenu').appendChild(schoolSuggestion);

Body:
So I have a keyup function that retrieves data from a MySQL table, and then displays it. However, it retrieves data again if a letter is changed.

See image below
How it currently is and In the inspector

What it should be doing is just replacing those suggestions with the new suggestions instead of adding it on to the list

EDIT: Shoaeb's solution works but not in the way he suggested.

document.getElementById('schoolListMenu').innerHTML="";

I added that line right after the keyup function is called. This clears the content in the div and replaces it with the updated content once the user has stopped typing. If the user presses a key again it will clear the div again and append the updated results.

edit2: Updated JS Code

var timeout = null;
function getSchool(schoolType){
    if(schoolType1.classList.contains('active') || schoolType2.classList.contains('active'))
    {
        schoolNameField.onkeyup = function(e)
        {
            document.getElementById('schoolListMenu').innerHTML="";
            clearTimeout(timeout);
            timeout = setTimeout(function() {
                var query = e.target.value;
                console.log(query);
                var xmlhttp = new XMLHttpRequest();
                xmlhttp.onreadystatechange = function() {
                    if (this.readyState === 4 && this.status === 200) {
                        var schoolResult = this.responseText;
                        schoolResult = schoolResult.split("|");
                        for(var i = 0; i < schoolResult.length; i++)
                        {
                            var schoolSuggestion = document.createElement('div');
                            schoolSuggestion.id = 'schoolSuggestion'+i;
                            schoolSuggestion.className = 'item';
                            schoolSuggestion.innerText = schoolResult[i];
                            document.getElementById('schoolListMenu').appendChild(schoolSuggestion);
                        }
                    }
                };
                xmlhttp.open("GET", "scripts/schoolLookup.php?type="+schoolType+"&name="+query, true);
                xmlhttp.send();
            }, 500);
        };
    }
}

How do I get it to replace the content instead of adding on new divs? I feel like I understand what the problem is and know what the solution is but I can't put it to words


问:
Using move semantics: rvalue reference as a method parameter
I would like to doublecheck my understanding of move semantics. Am I missing anything in my reasoning:

```<code>#include <iostream>

using std::cout;

struct A
{
    A() {cout<<"Constructor\n";}
    ~A() {cout<<"Desctuctor\n";}
    A(const A&) {cout<<"Copy Constructor\n";}
    A(A&&) noexcept {cout<<"Move Constructor\n";}
    int x{1};
};

int f1(A a)
{
    cout<<"f1(A a)\n";
    return a.x;
}

int f2 (A&& a)
{
    cout<<"f2 (A&& a)\n";
    return a.x;
}

int main()
{
  A a1, a2;
  f1(std::move(a1));
  f2(std::move(a2));
}
</code>```

Output:

```<code>Constructor
Constructor
Move Constructor
f1(A a)
Desctuctor
f2 (A&& a)
Desctuctor
Desctuctor
</code>```

From what I can see with f2(), I'm not creating any additional copies, even "light" move copies, which is cool.
So my understanding now is that if I'm going to use move semantics, I better always write functions/methods signature to accept r-values as to avoid any unnecessary copies at all. Or there is something else I'm missing ?

答:
You're almost always best just taking inputs you're going to keep by value (except for odd types which have very high costs of moves).

It maintains the same level of performance (in common scenarios) and keeps your code very simple to understand.   It also makes it very clear that your code is keeping the value (because it's guaranteed to get moved out of), as an rvalue reference doesn't enforce that.

As you can see, the timings and generated code are identical for your examples when the print statements are removed:  http://quick-bench.com/ADU4fzd0ISk0UrLboVhC-Pd7RmI

Body:
I would like to doublecheck my understanding of move semantics. Am I missing anything in my reasoning:

#include <iostream>

using std::cout;

struct A
{
    A() {cout<<"Constructor\n";}
    ~A() {cout<<"Desctuctor\n";}
    A(const A&) {cout<<"Copy Constructor\n";}
    A(A&&) noexcept {cout<<"Move Constructor\n";}
    int x{1};
};

int f1(A a)
{
    cout<<"f1(A a)\n";
    return a.x;
}

int f2 (A&& a)
{
    cout<<"f2 (A&& a)\n";
    return a.x;
}

int main()
{
  A a1, a2;
  f1(std::move(a1));
  f2(std::move(a2));
}

Output:

Constructor
Constructor
Move Constructor
f1(A a)
Desctuctor
f2 (A&& a)
Desctuctor
Desctuctor

From what I can see with f2(), I'm not creating any additional copies, even "light" move copies, which is cool.
So my understanding now is that if I'm going to use move semantics, I better always write functions/methods signature to accept r-values as to avoid any unnecessary copies at all. Or there is something else I'm missing ?


问:
Unable to store instance in JavaScript variable
I'm currently working on implementing a Stack in JavaScript using a LinkedList. However, I have an issue when instantiating a Node class. When I try to have a variable let newNode = new Node(x) I get undefined.

I'm not sure why that is but I would like to understand. If in the repl I run new Node(x) I get { val: -2, next: null } a node. But when I store it in a variable I get undefined let newNode = new Node(x) it returns undefined if I console newNode.

```<code>/**
 * initialize your data structure here.
 */
var MinStack = function() {
  this.size = 0;
  this.min = null;
  this.first = null;
};

var Node = function(val) {
  this.val = val;
  this.next = null;
}
/**
 * @param {number} x
 * @return {void}
 */
MinStack.prototype.push = function(x) {
  if(this.first == null) {
    this.first = new Node(x);
    this.min = this.first;
    this.size++;
    return
  }

  let newNode = new Node(x);
  if(newNode.val < this.min.val) {
    this.min = newNode.val;
  }
  let oldFirst = this.first;
  newNode.next = oldFirst;
  this.first = newNode;
  this.size++;
};
/**
 * @return {void}
 */
MinStack.prototype.pop = function() {
  if(this.first === null) {
    return;
  }
  if(this.min === this.first) {
    let current = this.first.next;
    this.min = current;
    while(current != null) {
      if(current.val < this.min.val || this.size === 2) {
        this.min = current;
      }
      current = current.next;
    }
  }
  this.first = this.first.next;
  this.size--;
  return
};
/**
 * @return {number}
 */
MinStack.prototype.top = function() {
  return this.first.val;
};
/**
 * @return {number}
 */
MinStack.prototype.getMin = function() {
    return this.min.val;
};
// ["MinStack","push","push","push","getMin","pop","top","getMin"]
// [[],[-2],[0],[-3],[],[],[],[]]

var obj = new MinStack()
obj.push(-2)
obj.push(0)
obj.push(-3)
console.log(obj.getMin())
obj.pop();
obj.top();
obj.getMin();
</code>```

This is what I get when I get to the debugger breakpoint

```<code>> let newNode = new Node(x)
undefined
> newNode
undefined
> new Node(x)
{ val: 0, next: null }
</code>```

What am I missing?

答:
"Node.js itself uses the repl module to provide its own interactive interface for executing JavaScript." https://nodejs.org/api/repl.html#repl_the_node_js_repl

According to the Node REPL, by default, commands that get evaluated to undefined, print undefined on the console

You can ignore undefined when you use command like let newNode = new Node(x). But the anomaly in your output is

```<code>> newNode
undefined
</code>```

The above should not have happened

Ideally it should be

```<code>> x = 0
0
> let newNode = new Node(x)
undefined
> newNode
Node { val: 0, next: null }
> new Node(x)
Node { val: 0, next: null }
</code>```

Body:
I'm currently working on implementing a Stack in JavaScript using a LinkedList. However, I have an issue when instantiating a Node class. When I try to have a variable let newNode = new Node(x) I get undefined.

I'm not sure why that is but I would like to understand. If in the repl I run new Node(x) I get { val: -2, next: null } a node. But when I store it in a variable I get undefined let newNode = new Node(x) it returns undefined if I console newNode.

/**
 * initialize your data structure here.
 */
var MinStack = function() {
  this.size = 0;
  this.min = null;
  this.first = null;
};

var Node = function(val) {
  this.val = val;
  this.next = null;
}
/**
 * @param {number} x
 * @return {void}
 */
MinStack.prototype.push = function(x) {
  if(this.first == null) {
    this.first = new Node(x);
    this.min = this.first;
    this.size++;
    return
  }

  let newNode = new Node(x);
  if(newNode.val < this.min.val) {
    this.min = newNode.val;
  }
  let oldFirst = this.first;
  newNode.next = oldFirst;
  this.first = newNode;
  this.size++;
};
/**
 * @return {void}
 */
MinStack.prototype.pop = function() {
  if(this.first === null) {
    return;
  }
  if(this.min === this.first) {
    let current = this.first.next;
    this.min = current;
    while(current != null) {
      if(current.val < this.min.val || this.size === 2) {
        this.min = current;
      }
      current = current.next;
    }
  }
  this.first = this.first.next;
  this.size--;
  return
};
/**
 * @return {number}
 */
MinStack.prototype.top = function() {
  return this.first.val;
};
/**
 * @return {number}
 */
MinStack.prototype.getMin = function() {
    return this.min.val;
};
// ["MinStack","push","push","push","getMin","pop","top","getMin"]
// [[],[-2],[0],[-3],[],[],[],[]]

var obj = new MinStack()
obj.push(-2)
obj.push(0)
obj.push(-3)
console.log(obj.getMin())
obj.pop();
obj.top();
obj.getMin();

This is what I get when I get to the debugger breakpoint

> let newNode = new Node(x)
undefined
> newNode
undefined
> new Node(x)
{ val: 0, next: null }

What am I missing?

Body:
"Node.js itself uses the repl module to provide its own interactive interface for executing JavaScript." https://nodejs.org/api/repl.html#repl_the_node_js_repl

According to the Node REPL, by default, commands that get evaluated to undefined, print undefined on the console

You can ignore undefined when you use command like let newNode = new Node(x). But the anomaly in your output is

> newNode
undefined

The above should not have happened

Ideally it should be

> x = 0
0
> let newNode = new Node(x)
undefined
> newNode
Node { val: 0, next: null }
> new Node(x)
Node { val: 0, next: null }


问:
Using filter() with across() to keep all rows of a data frame that include a missing value for any variable
Sometimes I want to view all rows in a data frame that will be dropped if I drop all rows that have a missing value for any variable. In this case, I'm specifically interested in how to do this with dplyr 1.0's across() function used inside of the filter() verb.

Here is an example data frame:

```<code>df <- tribble(
  ~id, ~x, ~y,
  1, 1, 0,
  2, 1, 1,
  3, NA, 1,
  4, 0, 0,
  5, 1, NA
)
</code>```

Code for keeping rows that DO NOT include any missing values is provided on the tidyverse website. Specifically, I can use:

```<code>df %>%
  filter(
    across(
      .cols = everything(),
      .fns = ~ !is.na(.x)
    )
  )
</code>```

Which returns:

```<code># A tibble: 3 x 3
     id     x     y
  <dbl> <dbl> <dbl>
1     1     1     0
2     2     1     1
3     4     0     0
</code>```

However, I can't figure out how to return the opposite -- rows with a missing value in any variable. The result I'm looking for is:

```<code># A tibble: 2 x 3
     id     x     y
  <dbl> <dbl> <dbl>
1     3    NA     1
2     5     1    NA
</code>```

My first thought was just to remove the !:

```<code>df %>%
  filter(
    across(
      .cols = everything(),
      .fns = ~ is.na(.x)
    )
  )
</code>```

But, that returns zero rows.

Of course, I can get the answer I want with this code if I know all variables that have a missing value ahead of time:

```<code>df %>%
  filter(is.na(x) | is.na(y))
</code>```

But, I'm looking for a solution that doesn't require me to know which variables have a missing value ahead of time. Additionally, I'm aware of how to do this with the filter_all() function:

```<code>df %>%
  filter_all(any_vars(is.na(.)))
</code>```

But, the filter_all() function has been superseded by the use of across() in an existing verb. See https://dplyr.tidyverse.org/articles/colwise.html

Other unsuccessful attempts I've made are:

```<code>df %>%
  filter(
    across(
      .cols = everything(),
      .fns = ~any_vars(is.na(.x))
    )
  )

df %>%
  filter(
    across(
      .cols = everything(),
      .fns = ~!!any_vars(is.na(.x))
    )
  )

df %>%
  filter(
    across(
      .cols = everything(),
      .fns = ~!!any_vars(is.na(.))
    )
  )

df %>%
  filter(
    across(
      .cols = everything(),
      .fns = ~any(is.na(.x))
    )
  )

df %>%
  filter(
    across(
      .cols = everything(),
      .fns = ~any(is.na(.))
    )
  )
</code>```

答:
HanOostdijk replied on the RStudio Community website with a solution that uses the across() function. He writes:

"In the same article you mention tidyverse website there is 'a trick' with the rowSums function. You can use that as:"

```<code>rowAny <- function(x) {
  rowSums(x) > 0
}

df %>%
  filter(
    rowAny(
      across(
       .cols = everything(),
       .fns = ~ is.na(.x)
      )
    )
  )
</code>```

@akrun points out in the comments below that this can be made more compact as:

```<code>df %>%
  filter(rowSums(across(everything(), ~ is.na(.))) > 0)
</code>```

Body:
Sometimes I want to view all rows in a data frame that will be dropped if I drop all rows that have a missing value for any variable. In this case, I'm specifically interested in how to do this with dplyr 1.0's across() function used inside of the filter() verb.

Here is an example data frame:

df <- tribble(
  ~id, ~x, ~y,
  1, 1, 0,
  2, 1, 1,
  3, NA, 1,
  4, 0, 0,
  5, 1, NA
)

Code for keeping rows that DO NOT include any missing values is provided on the tidyverse website. Specifically, I can use:

df %>%
  filter(
    across(
      .cols = everything(),
      .fns = ~ !is.na(.x)
    )
  )

Which returns:

# A tibble: 3 x 3
     id     x     y
  <dbl> <dbl> <dbl>
1     1     1     0
2     2     1     1
3     4     0     0

However, I can't figure out how to return the opposite -- rows with a missing value in any variable. The result I'm looking for is:

# A tibble: 2 x 3
     id     x     y
  <dbl> <dbl> <dbl>
1     3    NA     1
2     5     1    NA

My first thought was just to remove the !:

df %>%
  filter(
    across(
      .cols = everything(),
      .fns = ~ is.na(.x)
    )
  )

But, that returns zero rows.

Of course, I can get the answer I want with this code if I know all variables that have a missing value ahead of time:

df %>%
  filter(is.na(x) | is.na(y))

But, I'm looking for a solution that doesn't require me to know which variables have a missing value ahead of time. Additionally, I'm aware of how to do this with the filter_all() function:

df %>%
  filter_all(any_vars(is.na(.)))

But, the filter_all() function has been superseded by the use of across() in an existing verb. See https://dplyr.tidyverse.org/articles/colwise.html

Other unsuccessful attempts I've made are:

df %>%
  filter(
    across(
      .cols = everything(),
      .fns = ~any_vars(is.na(.x))
    )
  )

df %>%
  filter(
    across(
      .cols = everything(),
      .fns = ~!!any_vars(is.na(.x))
    )
  )

df %>%
  filter(
    across(
      .cols = everything(),
      .fns = ~!!any_vars(is.na(.))
    )
  )

df %>%
  filter(
    across(
      .cols = everything(),
      .fns = ~any(is.na(.x))
    )
  )

df %>%
  filter(
    across(
      .cols = everything(),
      .fns = ~any(is.na(.))
    )
  )

Body:
HanOostdijk replied on the RStudio Community website with a solution that uses the across() function. He writes:

"In the same article you mention tidyverse website there is 'a trick' with the rowSums function. You can use that as:"

rowAny <- function(x) {
  rowSums(x) > 0
}

df %>%
  filter(
    rowAny(
      across(
       .cols = everything(),
       .fns = ~ is.na(.x)
      )
    )
  )

@akrun points out in the comments below that this can be made more compact as:

df %>%
  filter(rowSums(across(everything(), ~ is.na(.))) > 0)


答:
This seems to be a Proguard problem.

Solution 1:

If you want to keep proguard activated,

add the below to proguard-rules.pro file

```<code>-keep class com.mobileer.** { *; }
</code>```

otherwise, if you don't want proguard activated

Solution 2:

set minifyEnabled false in build.gradle

Title: Android app error: Kotlin class not found but only on Release apk

Body:
I'm having a very strange bug that only happens on Release. If I install the app in Debug mode through Android Studio, everything works fine. If I change the bild variant to Release, I get this error right on the startup of the app:

2020-06-02 20:53:14.892 19248-19248/? A/DEBUG: *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** ***
2020-06-02 20:53:14.892 19248-19248/? A/DEBUG: Build fingerprint: 'motorola/griffin/griffin:8.0.0/OPL27.76-71-2-3/3:user/release-keys'
2020-06-02 20:53:14.892 19248-19248/? A/DEBUG: Revision: 'p3b0'
2020-06-02 20:53:14.892 19248-19248/? A/DEBUG: ABI: 'arm64'
2020-06-02 20:53:14.892 19248-19248/? A/DEBUG: pid: 19179, tid: 19179, name: om.stompai.kick  >>> com.stompai.kick <<<
2020-06-02 20:53:14.892 19248-19248/? A/DEBUG: signal 6 (SIGABRT), code -6 (SI_TKILL), fault addr --------
2020-06-02 20:53:14.893 19248-19248/? A/DEBUG: Abort message: 'thread.cc:2036] No pending exception expected: java.lang.ClassNotFoundException: Didn't find class "com.mobileer.androidfxlab.datatype.EffectDescription" on path: DexPathList[[zip file "/data/app/com.stompai.kick-2yS5YP_5sv5B-eZMR3oZbA==/base.apk"],nativeLibraryDirectories=[/data/app/com.stompai.kick-2yS5YP_5sv5B-eZMR3oZbA==/lib/arm64, /data/app/com.stompai.kick-2yS5YP_5sv5B-eZMR3oZbA==/base.apk!/lib/arm64-v8a, /system/lib64, /system/vendor/lib64]]'
2020-06-02 20:53:14.893 19248-19248/? A/DEBUG:     x0   0000000000000000  x1   0000000000004aeb  x2   0000000000000006  x3   0000000000000008
2020-06-02 20:53:14.893 19248-19248/? A/DEBUG:     x4   0000000000000000  x5   0000000000000000  x6   0000000000000000  x7   0080808080808080
2020-06-02 20:53:14.893 19248-19248/? A/DEBUG:     x8   0000000000000083  x9   f6d5a51ab7c22c2d  x10  0000000000000000  x11  0000000000000001
2020-06-02 20:53:14.893 19248-19248/? A/DEBUG:     x12  ffffffffffffffff  x13  0000000000000008  x14  ffffffffffffffff  x15  000017b556277360
2020-06-02 20:53:14.893 19248-19248/? A/DEBUG:     x16  0000007f881e12f8  x17  0000007f881829d4  x18  0000000000000020  x19  0000000000004aeb
2020-06-02 20:53:14.893 19248-19248/? A/DEBUG:     x20  0000000000004aeb  x21  0000007f77dc0800  x22  0000000000000058  x23  000000000000095c
2020-06-02 20:53:14.893 19248-19248/? A/DEBUG:     x24  0000000000000061  x25  0000007f6c157600  x26  000000000000095b  x27  0000000000000059
2020-06-02 20:53:14.893 19248-19248/? A/DEBUG:     x28  0000007fd10538a1  x29  0000007fd10535a0  x30  0000007f88136d24
2020-06-02 20:53:14.893 19248-19248/? A/DEBUG:     sp   0000007fd1053560  pc   0000007f881829dc  pstate 0000000060000000
2020-06-02 20:53:14.898 19248-19248/? A/DEBUG: backtrace:
2020-06-02 20:53:14.898 19248-19248/? A/DEBUG:     #00 pc 00000000000699dc  /system/lib64/libc.so (tgkill+8)
2020-06-02 20:53:14.898 19248-19248/? A/DEBUG:     #01 pc 000000000001dd20  /system/lib64/libc.so (abort+88)
2020-06-02 20:53:14.898 19248-19248/? A/DEBUG:     #02 pc 0000000000437c9c  /system/lib64/libart.so (_ZN3art7Runtime5AbortEPKc+528)
2020-06-02 20:53:14.898 19248-19248/? A/DEBUG:     #03 pc 00000000004383ac  /system/lib64/libart.so (_ZN3art7Runtime7AborterEPKc+24)
2020-06-02 20:53:14.899 19248-19248/? A/DEBUG:     #04 pc 0000000000522ab4  /system/lib64/libart.so (_ZN7android4base10LogMessageD1Ev+900)
2020-06-02 20:53:14.899 19248-19248/? A/DEBUG:     #05 pc 0000000000462858  /system/lib64/libart.so (_ZNK3art6Thread24AssertNoPendingExceptionEv+1144)
2020-06-02 20:53:14.902 19248-19248/? A/DEBUG:     #06 pc 0000000000127dac  /system/lib64/libart.so (_ZN3art11ClassLinker9FindClassEPNS_6ThreadEPKcNS_6HandleINS_6mirror11ClassLoaderEEE+64)
2020-06-02 20:53:14.903 19248-19248/? A/DEBUG:     #07 pc 0000000000311ec4  /system/lib64/libart.so (_ZN3art3JNI9FindClassEP7_JNIEnvPKc+1432)
2020-06-02 20:53:14.903 19248-19248/? A/DEBUG:     #08 pc 0000000000068698  /data/app/com.stompai.kick-2yS5YP_5sv5B-eZMR3oZbA==/lib/arm64/libfxlib.so (Java_com_mobileer_androidfxlab_NativeInterface_getEffects+88)
2020-06-02 20:53:14.903 19248-19248/? A/DEBUG:     #09 pc 000000000004590c  /data/app/com.stompai.kick-2yS5YP_5sv5B-eZMR3oZbA==/oat/arm64/base.odex (offset 0x2c000)

As you see, the error is

java.lang.ClassNotFoundException: Didn't find class "com.mobileer.androidfxlab.datatype.EffectDescription

This is a simply class located at

java/com/github/mobileer/androidfxlab/datatype/EffectDescription

I thought it had something to do with this being a Kotlin class located inside the /java folder so I moved it to /kotlin/com/mobileer/androidfxlab/... but the same error continues.

I have no clue on this problem. I tried cleaning an rebuilding the project, and also a friend of mine had the same problem on his computer, so this does not look like a build bug.

Body:
This seems to be a Proguard problem.

Solution 1:

If you want to keep proguard activated,

add the below to proguard-rules.pro file

-keep class com.mobileer.** { *; }

otherwise, if you don't want proguard activated

Solution 2:

set minifyEnabled false in build.gradle


问:
add.s $f8,$f10,$f12 in MIPS to binary
I'm trying to write

```<code>add.s $f8,$f10,$f12
</code>```

(MIPS) in binary. I got

```<code>01011 01010 01100 01010 01000 000000
</code>```

MARS compiles this as

```<code>010001  10000   01100   01010   01000   000000
</code>```

Not sure what went wrong. Help?

答:
First, you're only showing 31 digits.

Second, you have put into the opcode and fmt fields decimal numbers 11 and 10, but they are hex 11 and 10 (decimal 17 and 16).

At the top of the MIPS Green Sheet, first page, the header for the very last column says: (Hex).  We can also verify this by seeing some of the values in that column, e.g. the FUNCT code shows 1a for div and the OPCODE field shows 3d for sdc1.

On another note, the Green Sheet is super confusing, so you have to read it with care.  Take the "OPCODES, BASE CONVERSION, ASCII SYMBOLS" table, for example, which does binary <-> decimal <-> hex for 6 binary digits, while showing opcode and funct fields along with the ASCII chart — an extraordinary table.

Title: add.s $f8,$f10,$f12 in MIPS to binary

Body:
I'm trying to write

add.s $f8,$f10,$f12

(MIPS) in binary. I got

01011 01010 01100 01010 01000 000000

MARS compiles this as

010001  10000   01100   01010   01000   000000

Not sure what went wrong. Help?


问:
Gdiplus 64bit colors
I am creating a 64bit bitmap and wrapping it using Graphics object to draw over it.
Problem is Gdiplus Color class is only 32bit(each component is byte only i.e.max 255) so how can I draw over a 64bit image using gdiplus?
e.g.</p>

```<code>Bitmap bmp(100, 100, PixelFormat64bppARGB);

Graphics g(&bmp);
//how do I draw a red line now, if i use Color(255,0,0) it comes as almost dark black red
</code>```

答:
It seems Gdiplus doesn't support any 64-bit operations. An somehow easy way to still be able to use Gdiplus methods would be to split the image in two 32-bit images and operate on them seperately.

You could either split the ARGB channels into AARR and GGBB or use two 32-bit images with the lower and higher ARGB bits.

Both variants would need that you either write wrapping functions or split each call into two parts like this:

```<code>// This is what you want to do (ARGB, 16 bit per channel)
// g.DrawLine(new Pen(Color(0, 65535, 1024, 31), 1, 0, 0, 100, 100);

// AARR GGBB variant
gAARR.DrawLine(new Pen(Color(0,0,255,255), 1, 0, 0, 100, 100);
gGGBB.DrawLine(new Pen(Color(4,0,0,31), 1, 0, 0, 100, 100);

// ARGBhigh ARGBlow variant
gHigh.DrawLine(new Pen(Color(0,255,4,0), 1, 0, 0, 100, 100);
gLow.DrawLine(new Pen(Color(0,255,0,31), 1, 0, 0, 100, 100);
</code>```

Note that I used Color(A,R,G,B) order here and I'm not sure about it. According to the MSDN documentation, this must be changed to Color(R,G,B,A) instead. If you won't need the alpha channel, you should prefer the highlow variant as you should still be able to use Color(R,G,B) with it.

To display or save the results, you'll need to merge the 2 buffers.

ContentLicense: CC BY-SA 2.5

Title: Gdiplus 64bit colors

Body:
I am creating a 64bit bitmap and wrapping it using Graphics object to draw over it.
Problem is Gdiplus Color class is only 32bit(each component is byte only i.e.max 255) so how can I draw over a 64bit image using gdiplus?
e.g.

Bitmap bmp(100, 100, PixelFormat64bppARGB);

Graphics g(&bmp);
//how do I draw a red line now, if i use Color(255,0,0) it comes as almost dark black red

LastEditorDisplayName: Kris Erickson

Body:
It seems Gdiplus doesn't support any 64-bit operations. An somehow easy way to still be able to use Gdiplus methods would be to split the image in two 32-bit images and operate on them seperately.

You could either split the ARGB channels into AARR and GGBB or use two 32-bit images with the lower and higher ARGB bits.

Both variants would need that you either write wrapping functions or split each call into two parts like this:

// This is what you want to do (ARGB, 16 bit per channel)
// g.DrawLine(new Pen(Color(0, 65535, 1024, 31), 1, 0, 0, 100, 100);

// AARR GGBB variant
gAARR.DrawLine(new Pen(Color(0,0,255,255), 1, 0, 0, 100, 100);
gGGBB.DrawLine(new Pen(Color(4,0,0,31), 1, 0, 0, 100, 100);

// ARGBhigh ARGBlow variant
gHigh.DrawLine(new Pen(Color(0,255,4,0), 1, 0, 0, 100, 100);
gLow.DrawLine(new Pen(Color(0,255,0,31), 1, 0, 0, 100, 100);

Note that I used Color(A,R,G,B) order here and I'm not sure about it. According to the MSDN documentation, this must be changed to Color(R,G,B,A) instead. If you won't need the alpha channel, you should prefer the highlow variant as you should still be able to use Color(R,G,B) with it.

To display or save the results, you'll need to merge the 2 buffers.

OwnerDisplayName: schnaader

LastEditorDisplayName: schnaader


问:
Why do changes to an array 'B' in JavaScript spread to an array 'A' (which was used to define 'B' but thereafter never directly modified)?
I created a constant named 'alphabet' and assigned it to an array containing the first 5 letters of the alphabet. I then wanted to have a function that would add a number to each character in the array, to enumerate them. But, I didn't want the values in the original 'alphabet' array to be modified, so I created a 'temp' variable within my enumerating function and only made changes to that. However, any changes I made to 'temp' spread over to 'alphabet'. I don't understand why and I'd like to prevent that from happening.

Here's my code: (also available on CodePen)

```<code>const alphabet = ["a", "b", "c", "d", "e"];

function alphaPosition(seq) {
  //'temp' gets 'seq' to avoid making changes directly on the provided argument.
  let temp = seq;
  //adds indexes to each element in the 'temp' array:
  for (let i = 1; i <= temp.length; i++) {
    temp[i - 1] = temp[i - 1] + i;
  }
  return temp;
}

console.log(
  "Step 1. 'alphabet' array before running the 'alphaPosition' function:"
);
console.log(alphabet);
console.log(
  "Step 2. This is the final value of 'temp' in 'alphaPosition' after running the function. An index has been added to every element in the array, as expected:"
);
console.log(alphaPosition(alphabet));
console.log(
  "Step 3. Here's the 'alphabet' array after running 'alphaPosition'. Indexes have also been added to every element, despite not modifying the function argument directly:"
);
console.log(alphabet);
</code>```

Output:

```<code>/*
-> Step 1. 'alphabet' array before running the 'alphaPosition' function:
-> ["a", "b", "c", "d", "e"]
-> Step 2. This is the final value of 'temp' in 'alphaPosition' after running the function. An index has been added to every element in the array, as expected:
-> ["a1", "b2", "c3", "d4", "e5"]
-> Step 3. Here's the 'alphabet' array after running 'alphaPosition'. Indexes have also been added to every element, despite not modifying the function argument directly:
-> ["a1", "b2", "c3", "d4", "e5"]
*/
</code>```

Why do changes to 'temp' spread to 'alphabet'? I would expect that, since I defined 'alphabet' as a constant, it shouldn't even be possible to modify it. Also, I never make changes to it in my function. I only use it to define 'temp'. Is there any way to prevent these spreads from happening?

I experimented doing something similar with a numeric const instead of an array, and everything worked as intended:

```<code>const number = 10;

function numChange(n) {
  //'virtualN' gets 'n' to avoid making changes directly on the provided argument.
  let virtualN = n;
  //modify 'virtualN' multiple times to emulate what was done to the 'temp' array in the alphaPosition function.
  for (let i = 1; i <= 5; i++) {
    virtualN = "iteration" + i;
  }
  return virtualN;
}

console.log(
  "Step 1. See the value of 'number' before running the numChange function:"
);
console.log(number);
console.log(
  "Step 2. This is the final value of 'virtualN' in 'numChange(number)' after running the function. As expected, it's been modified from its initual value by the 'for' loop:"
);
console.log(numChange(number));
console.log(
  "Step 3. Finally, we can see the value of 'number' is still the same as before running the numChange function. As expected, only the value of virtualN changed while the argument 'n' suffered no modifications:"
);
console.log(number);
</code>```

Output:

```<code>/*
-> Step 1. See the value of 'number' before running the numChange function:
-> 10
-> Step 2. This is the final value of 'virtualN' in 'numChange(number)' after running the function. As expected, it's been modified from its initual value by the 'for' loop:
-> iteration5
-> Step 3. Finally, we can see the value of 'number' is still the same as before running the numChange function. As expected, only the value of virtualN changed while the argument 'n' suffered no modifications:
-> 10
*/
</code>```

Why does using an intermediary variable to avoid making changes to the original work for numbers and not for arrays?

I'd be extremely grateful for any help or clarification on this. I've added my code to this CodePen in case you'd like to tweak it or experiment more with it.
Thank you in advance for any help.

答:
This is about how assignment works in javascript. Given the following code:

const a = { foo: "bar" };
const b = a;
```

<p>Variables <code>a</code> and <code>b</code> both point to the same object. This means there is only one object in memory and mutating the object <code>a</code> points to will be reflected when you try to access the object using <code>b</code> and vice versa. For example:</p>

<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>const a = { foo: "bar" };
const b = a;

a.foo = "baz";

console.log(a);
console.log(b);</code>```

So now, how do we make this not happen? We can do this by assigning a shallow copy of a to b. This can be done a few different ways, the following uses the spread operator (...):

const a = { foo: "bar" };
const b = { ...a };

a.foo = "baz";

console.log(a);
console.log(b);```
</div>
</div>
</p>

<p>So now, there are two different objects in memory. You'll notice I called this a <em>shallow</em> copy, which is important: if you have deep objects you'll need to copy deeply to accomplish the same kind of decoupling.</p>

<p><strong>How to fix this in your specific case:</strong></p>

<p>The TLDR for your specific case is that your temp variable should be a shallow copy of the array, not a reference to the existing array:</p>

<pre class="lang-js prettyprint-override"><code>let temp = [...seq];
</code>```

Body:
I created a constant named 'alphabet' and assigned it to an array containing the first 5 letters of the alphabet. I then wanted to have a function that would add a number to each character in the array, to enumerate them. But, I didn't want the values in the original 'alphabet' array to be modified, so I created a 'temp' variable within my enumerating function and only made changes to that. However, any changes I made to 'temp' spread over to 'alphabet'. I don't understand why and I'd like to prevent that from happening.

Here's my code: (also available on CodePen)

const alphabet = ["a", "b", "c", "d", "e"];

function alphaPosition(seq) {
  //'temp' gets 'seq' to avoid making changes directly on the provided argument.
  let temp = seq;
  //adds indexes to each element in the 'temp' array:
  for (let i = 1; i <= temp.length; i++) {
    temp[i - 1] = temp[i - 1] + i;
  }
  return temp;
}

console.log(
  "Step 1. 'alphabet' array before running the 'alphaPosition' function:"
);
console.log(alphabet);
console.log(
  "Step 2. This is the final value of 'temp' in 'alphaPosition' after running the function. An index has been added to every element in the array, as expected:"
);
console.log(alphaPosition(alphabet));
console.log(
  "Step 3. Here's the 'alphabet' array after running 'alphaPosition'. Indexes have also been added to every element, despite not modifying the function argument directly:"
);
console.log(alphabet);

Output:

/*
-> Step 1. 'alphabet' array before running the 'alphaPosition' function:
-> ["a", "b", "c", "d", "e"]
-> Step 2. This is the final value of 'temp' in 'alphaPosition' after running the function. An index has been added to every element in the array, as expected:
-> ["a1", "b2", "c3", "d4", "e5"]
-> Step 3. Here's the 'alphabet' array after running 'alphaPosition'. Indexes have also been added to every element, despite not modifying the function argument directly:
-> ["a1", "b2", "c3", "d4", "e5"]
*/

Why do changes to 'temp' spread to 'alphabet'? I would expect that, since I defined 'alphabet' as a constant, it shouldn't even be possible to modify it. Also, I never make changes to it in my function. I only use it to define 'temp'. Is there any way to prevent these spreads from happening?

I experimented doing something similar with a numeric const instead of an array, and everything worked as intended:

const number = 10;

function numChange(n) {
  //'virtualN' gets 'n' to avoid making changes directly on the provided argument.
  let virtualN = n;
  //modify 'virtualN' multiple times to emulate what was done to the 'temp' array in the alphaPosition function.
  for (let i = 1; i <= 5; i++) {
    virtualN = "iteration" + i;
  }
  return virtualN;
}

console.log(
  "Step 1. See the value of 'number' before running the numChange function:"
);
console.log(number);
console.log(
  "Step 2. This is the final value of 'virtualN' in 'numChange(number)' after running the function. As expected, it's been modified from its initual value by the 'for' loop:"
);
console.log(numChange(number));
console.log(
  "Step 3. Finally, we can see the value of 'number' is still the same as before running the numChange function. As expected, only the value of virtualN changed while the argument 'n' suffered no modifications:"
);
console.log(number);

Output:

/*
-> Step 1. See the value of 'number' before running the numChange function:
-> 10
-> Step 2. This is the final value of 'virtualN' in 'numChange(number)' after running the function. As expected, it's been modified from its initual value by the 'for' loop:
-> iteration5
-> Step 3. Finally, we can see the value of 'number' is still the same as before running the numChange function. As expected, only the value of virtualN changed while the argument 'n' suffered no modifications:
-> 10
*/

Why does using an intermediary variable to avoid making changes to the original work for numbers and not for arrays?

I'd be extremely grateful for any help or clarification on this. I've added my code to this CodePen in case you'd like to tweak it or experiment more with it.
Thank you in advance for any help.

Body:
This is about how assignment works in javascript. Given the following code:

const a = { foo: "bar" };
const b = a;

Variables a and b both point to the same object. This means there is only one object in memory and mutating the object a points to will be reflected when you try to access the object using b and vice versa. For example:

const a = { foo: "bar" };
const b = a;

a.foo = "baz";

console.log(a);
console.log(b);

So now, how do we make this not happen? We can do this by assigning a shallow copy of a to b. This can be done a few different ways, the following uses the spread operator (...):

const a = { foo: "bar" };
const b = { ...a };

a.foo = "baz";

console.log(a);
console.log(b);

So now, there are two different objects in memory. You'll notice I called this a shallow copy, which is important: if you have deep objects you'll need to copy deeply to accomplish the same kind of decoupling.

How to fix this in your specific case:

The TLDR for your specific case is that your temp variable should be a shallow copy of the array, not a reference to the existing array:

let temp = [...seq];


问:
PlatformException(error, java.lang.IllegalStateException: Trying to create a platform view of unregistered type: plugins.flutter.io/webview
I have tryed the next three package for the web view in my flutter widget:

https://pub.dev/packages/webview_flutter

https://pub.dev/packages/flutter_inappwebview

https://pub.dev/packages/flutter_webview_plugin

But always have the same error. The error is the next:

```<code>E/flutter (20538): [ERROR:flutter/lib/ui/ui_dart_state.cc(157)] Unhandled Exception: PlatformException(error, java.lang.IllegalStateException: Trying to create a platform view of unregistered type: plugins.flutter.io/webview
E/flutter (20538):  at io.flutter.plugin.platform.PlatformViewsController$1.createPlatformView(PlatformViewsController.java:97)
E/flutter (20538):  at io.flutter.embedding.engine.systemchannels.PlatformViewsChannel$1.create(PlatformViewsChannel.java:95)
E/flutter (20538):  at io.flutter.embedding.engine.systemchannels.PlatformViewsChannel$1.onMethodCall(PlatformViewsChannel.java:59)
E/flutter (20538):  at io.flutter.plugin.common.MethodChannel$IncomingMethodCallHandler.onMessage(MethodChannel.java:226)
E/flutter (20538):  at io.flutter.embedding.engine.dart.DartMessenger.handleMessageFromDart(DartMessenger.java:85)
E/flutter (20538):  at io.flutter.embedding.engine.FlutterJNI.handlePlatformMessage(FlutterJNI.java:631)
E/flutter (20538):  at android.os.MessageQueue.nativePollOnce(Native Method)
E/flutter (20538):  at android.os.MessageQueue.next(MessageQueue.java:336)
E/flutter (20538):  at android.os.Looper.loop(Looper.java:174)
E/flutter (20538):  at android.app.ActivityThread.main(ActivityThread.java:7356)
E/flutter (20538):  at java.lang.reflect.Method.invoke(Native Method)
E/flutter (20538):  at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:492)
E/flutter (20538):  at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:930)
E/flutter (20538): , null)
E/flutter (20538): #0      StandardMethodCodec.decodeEnvelope (package:flutter/src/services/message_codecs.dart:569:7)
E/flutter (20538): #1      MethodChannel._invokeMethod (package:flutter/src/services/platform_channel.dart:156:18)
E/flutter (20538): <asynchronous suspension>
E/flutter (20538): #2      MethodChannel.invokeMethod (package:flutter/src/services/platform_channel.dart:329:12)
E/flutter (20538): #3      AndroidViewController._create (package:flutter/src/services/platform_views.dart:633:54)
E/flutter (20538): #4      AndroidViewController.setSize (package:flutter/src/services/platform_views.dart:550:14)
E/flutter (20538): #5      RenderAndroidView._sizePlatformView (package:flutter/src/rendering/platform_view.dart:175:29)
E/flutter (20538): #6      RenderAndroidView.performResize (package:flutter/src/rendering/platform_view.dart:156:5)
E/flutter (20538): #7      RenderObject.layout (package:flutter/src/rendering/object.dart:1746:9)
E/flutter (20538): #8      RenderProxyBoxMixin.performLayout (package:flutter/src/rendering/proxy_box.dart:111:13)
E/flutter (20538): #9      RenderObject.layout (package:flutter/src/rendering/object.dart:1767:7)
E/flutter (20538): #10     RenderProxyBoxMixin.performLayout (package:flutter/src/rendering/proxy_box.dart:111:13)
E/flutter (20538): #11     RenderObject.layout (package:flutter/src/rendering/object.dart:1767:7)
E/flutter (20538): #12     RenderFlex.performLayout (package:flutter/src/rendering/flex.dart:808:17)
E/flutter (20538): #13     RenderObject.layout (package:flutter/src/rendering/object.dart:1767:7)
E/flutter (20538): #14     MultiChildLayoutDelegate.layoutChild (package:flutter/src/rendering/custom_layout.dart:171:11)
E/flutter (20538): #15     _ScaffoldLayout.performLayout (package:flutter/src/material/scaffold.dart:484:7)
E/flutter (20538): #16     MultiChildLayoutDelegate._callPerformLayout (package:flutter/src/rendering/custom_layout.dart:240:7)
E/flutter (20538): #17     RenderCustomMultiChildLayoutBox.performLayout (package:flutter/src/rendering/custom_layout.dart:399:14)
E/flutter (20538): #18     RenderObject.layout (package:flutter/src/rendering/object.dart:1767:7)
E/flutter (20538): #19     RenderProxyBoxMixin.performLayout (package:flutter/src/rendering/proxy_box.dart:111:13)
E/flutter (20538): #20     RenderObject.layout (package:flutter/src/rendering/object.dart:1767:7)
E/flutter (20538): #21     RenderProxyBoxMixin.performLayout (package:flutter/src/rendering/proxy_box.dart:111:13)
E/flutter (20538): #22     _RenderCustomClip.performLayout (package:flutter/src/rendering/proxy_box.dart:1248:11)
E/flutter (20538): #23     RenderObject.layout (package:flutter/src/rendering/object.dart:1767:7)
E/flutter (20538): #24     RenderProxyBoxMixin.performLayout (package:flutter/src/rendering/proxy_box.dart:111:13)
E/flutter (20538): #25     RenderObject.layout (package:flutter/src/rendering/object.dart:1767:7)
E/flutter (20538): #26     RenderProxyBoxMixin.performLayout (package:flutter/src/rendering/proxy_box.dart:111:13)
E/flutter (20538): #27     RenderObject.layout (package:flutter/src/rendering/object.dart:1767:7)
E/flutter (20538): #28     RenderProxyBoxMixin.performLayout (package:flutter/src/rendering/proxy_box.dart:111:13)
E/flutter (20538): #29     RenderObject.layout (package:flutter/src/rendering/object.dart:1767:7)
E/flutter (20538): #30     RenderProxyBoxMixin.performLayout (packa
</code>```

I have also tryed to change minSdkVersion 20 but have the same error, which is mentioned here.

This is my 'flutter doctor -v'

```<code>/Users/taz/Desktop/flutter/bin/flutter doctor --verbose
Unable to find any JVMs matching version "1.8".
Unable to find any JVMs matching version "1.8".
[✓] Flutter (Channel beta, v1.17.0-3.2.pre, on Mac OS X 10.15.4 19E287, locale en-GE)
    • Flutter version 1.17.0-3.2.pre at /Users/taz/Desktop/flutter
    • Framework revision 2a7bc389f2 (3 days ago), 2020-04-21 20:34:20 -0700
    • Engine revision 4c8c31f591
    • Dart version 2.8.0 (build 2.8.0-dev.20.10)

Unable to find any JVMs matching version "1.8".
[!] Android toolchain - develop for Android devices (Android SDK version 29.0.2)
    • Android SDK at /Users/taz/Library/Android/sdk
    • Platform android-29, build-tools 29.0.2
    • Java binary at: /usr/bin/java
    • Java version Java(TM) SE Runtime Environment 18.9 (build 11.0.4+10-LTS)
    ✗ Android license status unknown.
      Try re-installing or updating your Android SDK Manager.
      See https://developer.android.com/studio/#downloads or visit visit https://flutter.dev/docs/get-started/install/macos#android-setup for detailed instructions.

[✓] Xcode - develop for iOS and macOS (Xcode 11.4.1)
    • Xcode at /Applications/Xcode.app/Contents/Developer
    • Xcode 11.4.1, Build version 11E503a
    • CocoaPods version 1.8.3

[!] Android Studio (not installed)
    • Android Studio not found; download from https://developer.android.com/studio/index.html
      (or visit https://flutter.dev/docs/get-started/install/macos#android-setup for detailed instructions).

[!] IntelliJ IDEA Community Edition (version 2020.1)
    • IntelliJ at /Applications/IntelliJ IDEA CE.app
    ✗ Flutter plugin not installed; this adds Flutter specific functionality.
    ✗ Dart plugin not installed; this adds Dart specific functionality.
    • For information about installing plugins, see
      https://flutter.dev/intellij-setup/#installing-the-plugins

[✓] Connected device (1 available)
    • Android SDK built for x86 • emulator-5554 • android-x86 • Android 10 (API 29) (emulator)

! Doctor found issues in 3 categories.
Process finished with exit code 0
</code>```

What I can do? :)

答:
I have updated my plugin flutter_inappwebview! Latest release is 3.3.0+3 at the time of this writing.
It has a lot of new events, methods, and options to control WebViews.

Body:
I have tryed the next three package for the web view in my flutter widget:

https://pub.dev/packages/webview_flutter

https://pub.dev/packages/flutter_inappwebview

https://pub.dev/packages/flutter_webview_plugin

But always have the same error. The error is the next:

E/flutter (20538): [ERROR:flutter/lib/ui/ui_dart_state.cc(157)] Unhandled Exception: PlatformException(error, java.lang.IllegalStateException: Trying to create a platform view of unregistered type: plugins.flutter.io/webview
E/flutter (20538):  at io.flutter.plugin.platform.PlatformViewsController$1.createPlatformView(PlatformViewsController.java:97)
E/flutter (20538):  at io.flutter.embedding.engine.systemchannels.PlatformViewsChannel$1.create(PlatformViewsChannel.java:95)
E/flutter (20538):  at io.flutter.embedding.engine.systemchannels.PlatformViewsChannel$1.onMethodCall(PlatformViewsChannel.java:59)
E/flutter (20538):  at io.flutter.plugin.common.MethodChannel$IncomingMethodCallHandler.onMessage(MethodChannel.java:226)
E/flutter (20538):  at io.flutter.embedding.engine.dart.DartMessenger.handleMessageFromDart(DartMessenger.java:85)
E/flutter (20538):  at io.flutter.embedding.engine.FlutterJNI.handlePlatformMessage(FlutterJNI.java:631)
E/flutter (20538):  at android.os.MessageQueue.nativePollOnce(Native Method)
E/flutter (20538):  at android.os.MessageQueue.next(MessageQueue.java:336)
E/flutter (20538):  at android.os.Looper.loop(Looper.java:174)
E/flutter (20538):  at android.app.ActivityThread.main(ActivityThread.java:7356)
E/flutter (20538):  at java.lang.reflect.Method.invoke(Native Method)
E/flutter (20538):  at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:492)
E/flutter (20538):  at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:930)
E/flutter (20538): , null)
E/flutter (20538): #0      StandardMethodCodec.decodeEnvelope (package:flutter/src/services/message_codecs.dart:569:7)
E/flutter (20538): #1      MethodChannel._invokeMethod (package:flutter/src/services/platform_channel.dart:156:18)
E/flutter (20538): <asynchronous suspension>
E/flutter (20538): #2      MethodChannel.invokeMethod (package:flutter/src/services/platform_channel.dart:329:12)
E/flutter (20538): #3      AndroidViewController._create (package:flutter/src/services/platform_views.dart:633:54)
E/flutter (20538): #4      AndroidViewController.setSize (package:flutter/src/services/platform_views.dart:550:14)
E/flutter (20538): #5      RenderAndroidView._sizePlatformView (package:flutter/src/rendering/platform_view.dart:175:29)
E/flutter (20538): #6      RenderAndroidView.performResize (package:flutter/src/rendering/platform_view.dart:156:5)
E/flutter (20538): #7      RenderObject.layout (package:flutter/src/rendering/object.dart:1746:9)
E/flutter (20538): #8      RenderProxyBoxMixin.performLayout (package:flutter/src/rendering/proxy_box.dart:111:13)
E/flutter (20538): #9      RenderObject.layout (package:flutter/src/rendering/object.dart:1767:7)
E/flutter (20538): #10     RenderProxyBoxMixin.performLayout (package:flutter/src/rendering/proxy_box.dart:111:13)
E/flutter (20538): #11     RenderObject.layout (package:flutter/src/rendering/object.dart:1767:7)
E/flutter (20538): #12     RenderFlex.performLayout (package:flutter/src/rendering/flex.dart:808:17)
E/flutter (20538): #13     RenderObject.layout (package:flutter/src/rendering/object.dart:1767:7)
E/flutter (20538): #14     MultiChildLayoutDelegate.layoutChild (package:flutter/src/rendering/custom_layout.dart:171:11)
E/flutter (20538): #15     _ScaffoldLayout.performLayout (package:flutter/src/material/scaffold.dart:484:7)
E/flutter (20538): #16     MultiChildLayoutDelegate._callPerformLayout (package:flutter/src/rendering/custom_layout.dart:240:7)
E/flutter (20538): #17     RenderCustomMultiChildLayoutBox.performLayout (package:flutter/src/rendering/custom_layout.dart:399:14)
E/flutter (20538): #18     RenderObject.layout (package:flutter/src/rendering/object.dart:1767:7)
E/flutter (20538): #19     RenderProxyBoxMixin.performLayout (package:flutter/src/rendering/proxy_box.dart:111:13)
E/flutter (20538): #20     RenderObject.layout (package:flutter/src/rendering/object.dart:1767:7)
E/flutter (20538): #21     RenderProxyBoxMixin.performLayout (package:flutter/src/rendering/proxy_box.dart:111:13)
E/flutter (20538): #22     _RenderCustomClip.performLayout (package:flutter/src/rendering/proxy_box.dart:1248:11)
E/flutter (20538): #23     RenderObject.layout (package:flutter/src/rendering/object.dart:1767:7)
E/flutter (20538): #24     RenderProxyBoxMixin.performLayout (package:flutter/src/rendering/proxy_box.dart:111:13)
E/flutter (20538): #25     RenderObject.layout (package:flutter/src/rendering/object.dart:1767:7)
E/flutter (20538): #26     RenderProxyBoxMixin.performLayout (package:flutter/src/rendering/proxy_box.dart:111:13)
E/flutter (20538): #27     RenderObject.layout (package:flutter/src/rendering/object.dart:1767:7)
E/flutter (20538): #28     RenderProxyBoxMixin.performLayout (package:flutter/src/rendering/proxy_box.dart:111:13)
E/flutter (20538): #29     RenderObject.layout (package:flutter/src/rendering/object.dart:1767:7)
E/flutter (20538): #30     RenderProxyBoxMixin.performLayout (packa

I have also tryed to change minSdkVersion 20 but have the same error, which is mentioned here.

This is my 'flutter doctor -v'

/Users/taz/Desktop/flutter/bin/flutter doctor --verbose
Unable to find any JVMs matching version "1.8".
Unable to find any JVMs matching version "1.8".
[✓] Flutter (Channel beta, v1.17.0-3.2.pre, on Mac OS X 10.15.4 19E287, locale en-GE)
    • Flutter version 1.17.0-3.2.pre at /Users/taz/Desktop/flutter
    • Framework revision 2a7bc389f2 (3 days ago), 2020-04-21 20:34:20 -0700
    • Engine revision 4c8c31f591
    • Dart version 2.8.0 (build 2.8.0-dev.20.10)

Unable to find any JVMs matching version "1.8".
[!] Android toolchain - develop for Android devices (Android SDK version 29.0.2)
    • Android SDK at /Users/taz/Library/Android/sdk
    • Platform android-29, build-tools 29.0.2
    • Java binary at: /usr/bin/java
    • Java version Java(TM) SE Runtime Environment 18.9 (build 11.0.4+10-LTS)
    ✗ Android license status unknown.
      Try re-installing or updating your Android SDK Manager.
      See https://developer.android.com/studio/#downloads or visit visit https://flutter.dev/docs/get-started/install/macos#android-setup for detailed instructions.

[✓] Xcode - develop for iOS and macOS (Xcode 11.4.1)
    • Xcode at /Applications/Xcode.app/Contents/Developer
    • Xcode 11.4.1, Build version 11E503a
    • CocoaPods version 1.8.3

[!] Android Studio (not installed)
    • Android Studio not found; download from https://developer.android.com/studio/index.html
      (or visit https://flutter.dev/docs/get-started/install/macos#android-setup for detailed instructions).

[!] IntelliJ IDEA Community Edition (version 2020.1)
    • IntelliJ at /Applications/IntelliJ IDEA CE.app
    ✗ Flutter plugin not installed; this adds Flutter specific functionality.
    ✗ Dart plugin not installed; this adds Dart specific functionality.
    • For information about installing plugins, see
      https://flutter.dev/intellij-setup/#installing-the-plugins

[✓] Connected device (1 available)
    • Android SDK built for x86 • emulator-5554 • android-x86 • Android 10 (API 29) (emulator)

! Doctor found issues in 3 categories.
Process finished with exit code 0

What I can do? :)