Why Can't I Access the Array with Index Directly

Why can't I access the array with index directly?

If an object is converted to an array, the result is an array whose elements are the object's properties. The keys are the member variable names, with a few notable exceptions: integer properties are unaccessible; private variables have the class name prepended to the variable name; protected variables have a '*' prepended to the variable name. These prepended values have null bytes on either side.

http://php.net/manual/en/language.types.array.php#language.types.array.casting

Try var_dump(bin2hex($arrKeys[8])) for enlightenment. Also see the example in the above linked manual.

Can't access array index in React

Let's go through your example from the beginning:

import { Link, BrowserRouter, Route } from "react-router-dom";
export default function App() {
return (
<div className="App">
<BrowserRouter>
<MonthName />
<Route path="/yearMonth" component={YearMonth} />
</BrowserRouter>
</div>
);
}

let month = ["Jan", "Feb", "March"];

const MonthName = () => {
return (
<>
{month.map((nameOfMonth, index) => (
<div key={index} onClick={() => YearMonth(index)}>
<Link to="/yearMonth">
<div>
<h3>{nameOfMonth}</h3>
</div>
</Link>
</div>
))}
</>
);
};

const YearMonth = (index) => {
return <div>{console.log(index)}</div>;
};

Our goal is to create an app, that displays a list of month-names as hyperlinks (MonthName Component), and on clicking any of those links, we should navigate to the YearMonth component.

Now, what happens when a link of a month is clicked. Two events are generated, a routing event and an onClick event registered in a div. And both events are passed to the functional component YearMonth.

So, when the onClick event executes, it passes the current index into the functional component, and therefore it gets logged.

Now, when routing event is triggered, the statement

<Route path="/yearMonth" component={YearMonth} />

is executed, and component YearMonth is rendered. But when using, react-routing mechanism, the Route components always pass a routing object to the component they render, as a function parameter. In this case, the YearMonth component. And since the YearMonth component accepts a single parameter, the index parameter
now points to this object and therefore it gets logged.

A simple way to solve this is to replace the YearMonth component, in the onClick handler with a new function, and remove logging from the YearMonth component.

import { Link, BrowserRouter, Route } from "react-router-dom";
export default function App() {
return (
<div className="App">
<BrowserRouter>
<MonthName />
<Route path="/yearMonth" component={YearMonth} />
</BrowserRouter>
</div>
);
}

let month = ["Jan", "Feb", "March"];

function yearMonth(index){
console.log(index);
}

const MonthName = () => {
return (
<>
{month.map((nameOfMonth, index) => (
<div key={index} onClick={() => yearMonth(index)}>
<Link to="/yearMonth">
<div>
<h3>{nameOfMonth}</h3>
</div>
</Link>
</div>
))}
</>
);
};

const YearMonth = () => {
return <div>Hi</div>;
};

To learn more about how routing works, follow this article.

Can't access the Value in PHP array via index

I think don't need for each loop just write like this I hope it will work

end($Data);  
$last = key($Data);
$last_element = $Data[$last];

Why can't you access this array with index?

In JavaScript, the length of an array is always one more than the largest numeric (integer) property name. Arrays can have properties whose names are not numeric, but they don't count towards the length of the array (and they are ignored in some other important situations).

Object property names are always strings, but strings that are non-negative integer values when interpreted as numbers are special in arrays. Accessing properties with numeric values works because the numbers are first converted to strings; thus box[0] and box['0'] do exactly the same thing.

Accessing an array out of bounds gives no error, why?

Welcome to every C/C++ programmer's bestest friend: Undefined Behavior.

There is a lot that is not specified by the language standard, for a variety of reasons. This is one of them.

In general, whenever you encounter undefined behavior, anything might happen. The application may crash, it may freeze, it may eject your CD-ROM drive or make demons come out of your nose. It may format your harddrive or email all your porn to your grandmother.

It may even, if you are really unlucky, appear to work correctly.

The language simply says what should happen if you access the elements within the bounds of an array. It is left undefined what happens if you go out of bounds. It might seem to work today, on your compiler, but it is not legal C or C++, and there is no guarantee that it'll still work the next time you run the program. Or that it hasn't overwritten essential data even now, and you just haven't encountered the problems, that it is going to cause — yet.

As for why there is no bounds checking, there are a couple aspects to the answer:

  • An array is a leftover from C. C arrays are about as primitive as you can get. Just a sequence of elements with contiguous addresses. There is no bounds checking because it is simply exposing raw memory. Implementing a robust bounds-checking mechanism would have been almost impossible in C.
  • In C++, bounds-checking is possible on class types. But an array is still the plain old C-compatible one. It is not a class. Further, C++ is also built on another rule which makes bounds-checking non-ideal. The C++ guiding principle is "you don't pay for what you don't use". If your code is correct, you don't need bounds-checking, and you shouldn't be forced to pay for the overhead of runtime bounds-checking.
  • So C++ offers the std::vector class template, which allows both. operator[] is designed to be efficient. The language standard does not require that it performs bounds checking (although it does not forbid it either). A vector also has the at() member function which is guaranteed to perform bounds-checking. So in C++, you get the best of both worlds if you use a vector. You get array-like performance without bounds-checking, and you get the ability to use bounds-checked access when you want it.

PHP Issue accessing array of objects by index - not working but seems like it should

Well. I'm an idiot. Thanks to everyone that took a look. I'm sorry I wasted your time.

The correct method for accessing the data I need is in fact:

$ResponseInfo->bundle[0]->building[0]->airConditioning;

adjusted of course to the correct variables and members. The reason I was having problems is that I got tunnel vision and when I tried to reduce my code to the simplest elements, I didn't do so completely.

In particular, the code I'm trying to debug is called repeatedly in a loop to pull property information and when I simplified things I forgot that. My test was pulling data for five properties and I got fixated on the first one, who's data was correct, and was verified to work repeatedly by me and others.

The second property in the loop however, didn't play quite so nice. As it turns out, the JSON data being returned for that property is in fact missing the elements I needed. That of course is a completely different issue.

Just because an error was thrown, doesn't necessarily mean it was the first iteration of the loop that caused it and I lost sight of that. The code I'm working on though is so modularized though that the loop that was my nemesis was quite removed from the routines I was focused on.

I probably should have just deleted the question, but I figured those that took time to look at it would appreciate a follow up, and maybe it will help someone else think about the bigger picture as well when troubleshooting.

Thanks again all.
Steve

can't access array index in batch file

You've got your order of delayed expansion inverted. Where you have %MY_LIST[!COUNTER!]%, the interpreter hasn't expanded the inner portion at the time it attempts to expand the outer. You need to find another way to expand !COUNTER! before using it as your array index, and to delay expansion of !MY_LIST[n]! even longer than that of !COUNTER!. Here's one way:

for %%A in (A B C) do (

for %%I in ("!COUNTER!") do ECHO %%A=!MY_LIST[%%~I]!
set /A COUNTER += 1
)

How to access of a array with objects if i dont know the array key/index?

You could build an object with all objects of the array. Then take the key of the wanted object for access.

var array = [        { foo: { id: 1, name: 'foo' } },        { bar: { id: 2, name: 'bar' } },        { baz: { id: 3, name: 'baz' } }    ],    object = Object.assign(...array);
console.log(object.foo.id);console.log(object);
.as-console-wrapper { max-height: 100% !important; top: 0; }

Accessing Array by index in bash doesn't work correctly if array is from a sourced file

The problem has nothing to do with sourcing; it's happening because the assignment numbers=${sourced_numbers[@]} doesn't do what you think it does. It converts the array (sourced_numbers) into a simple string, and stores that in the first element of numbers (leaving "two" "three" in the next two elements). To copy it as an array, use numbers=("${sourced_numbers[@]}") instead.

BTW, for number in ${numbers[@]} is the wrong way to loop through an array's elements, because it'll break on whitespace in the elements (in this case, the array contains "one two three" "two" "three", but the loop runs for "one", "two", "three", "two", "three"). Use for number in "${numbers[@]}" instead. Actually, it's good to get in the habit of double-quoting pretty much all variable substitutions (e.g. echo "${numbers[${i}]}"), as this is not the only place where leaving them unquoted could cause trouble.



Related Topics



Leave a reply



Submit